Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Try this:</p> <pre><code>SELECT table_a.*, COALESCE(table_b.full_name,table_c.full_name) AS full_name FROM table_a LEFT OUTER JOIN table_b ON table_b.user_id = table_a.user_id LEFT OUTER JOIN table_c ON table_c.user_id = table_a.user_id WHERE 1; </code></pre> <p>It uses the <code>LEFT OUTER JOIN</code>, which means that it joins it to <code>table_b</code> on the given condition. However, for each row in <code>table_a</code>, whether it finds a matching row in <code>table_b</code> or not, it will return the <code>table_a</code> row. If it does not find a matching row, the <code>table_b</code> columns are just NULL. Same thing with <code>table_c</code>.</p> <p>Then, we just select all the <code>table_a</code> columns. However, we now have two <code>full_name</code> columns, one from <code>table_b</code> and one from <code>table_c</code>. We use <code>COALESCE</code> to merge them.</p> <p><code>COALESCE</code> returns the first non-<code>NULL</code> value.</p> <p>Since we know that there is either a matching row in <code>table_b</code> or a matching row in <code>table_c</code>, it is not a problem. However, it would be a problem if somehow you allows a matching row to be found in both <code>table_b</code> and <code>table_c</code>.</p> <p>The risk can be mitigated by adding additional <code>ON</code> clause conditions to get:</p> <pre><code>SELECT table_a.*, COALESCE(table_b.full_name,table_c.full_name) AS full_name FROM table_a LEFT OUTER JOIN table_b ON table_b.user_id = table_a.user_id AND table_a.user_type = 1 LEFT OUTER JOIN table_c ON table_c.user_id = table_a.user_id AND table_a.user_type = 2 WHERE 1; </code></pre> <p>Still, you will need to make sure only 1 row is present for each user in <code>table_b</code> and <code>table_c</code>.</p> <hr> <p>Instead of <code>COALESCE</code> you can optionally use <code>CASE</code> like:</p> <pre><code>SELECT table_a.*, CASE user_type WHEN 1 THEN table_b.full_name ELSE table_c.full_name END AS full_name ... </code></pre> <p>or use an <code>IF</code> function like: SELECT table_a.*, IF(user_type=1,table_b.full_name,table_c.full_name) AS full_name ...</p>
 

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