Note that there are some explanatory texts on larger screens.

plurals
  1. POLEFT OUTER JOIN vs SUBSELECT in MySQL
    primarykey
    data
    text
    <p>I have a table say <code>table1</code> which has 3 columns <code>column1, column2 and column3</code>.</p> <p>The <code>column1</code> and <code>column2</code> are a <code>FOREIGN KEY</code> with 2 other tables. However the data in <code>column3</code> is from n number of tables. </p> <p>For e.g. Let us consider Facebook. To display the activities it might maintain a table which could have <code>user1 photoliked photo1</code> or <code>user1 statusliked status1</code>. So in this case <code>column3</code> cannot be a <code>FOREIGN KEY</code> with a specific table.</p> <p>Now there are 2 ways of getting real data -</p> <p>1st way -</p> <pre><code>SELECT user_id, verb_id, CASE WHEN verb_id = photoliked THEN (SELECT photo_name FROM photos WHERE photo_id = column3) -- getting the desired data from the third column WHEN verb_id = statusliked THEN (SELECT status FROM statustable WHERE status_id = column3) ELSE '' END AS performedon FROM table1 JOIN table2 ON user_id = user_id -- joining the first column JOIN table3 ON verb_id = verb_id -- joining the second column </code></pre> <p>2nd way -</p> <pre><code>SELECT user_id, verb_id, CASE WHEN verb_id = photoliked THEN p.photo_name WHEN verb_id = statusliked THEN s.status ELSE '' END AS performedon FROM table1 JOIN table2 ON user_id = user_id -- joining the first column JOIN table3 ON verb_id = verb_id -- joining the second column LEFT JOIN photos p ON p.photo_id = column3 -- joining the column3 with specific table LEFT JOIN statustable s ON s.status_id = column3 </code></pre> <p><strong>Question</strong></p> <p>Which of the 2 ways is better to retrieve data? and which of the 2 queries is less expensive? </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload