Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL join to multipe columns
    primarykey
    data
    text
    <p>I have tables like this:</p> <pre><code>tbl_base id primary_id aaaa bbbb cccc dddd eeee tbl_current id current_id aaaa bbbb qqqq cccc dddd zzzz tbl_results id value aaaa 10 cccc 20 dddd 50 zzzz 10 eeee 5 </code></pre> <p>I have a table of results (<code>tbl_results</code>) that match to a given ID. I want to join this data to <code>tbl_base</code>. Unfortunately, there are four possible ID's that could appear in tbl_results:</p> <ol> <li>tbl_base.id </li> <li>tbl_base.primary_id </li> <li>tbl_current.current_id (tbl_current.id = tbl_base.id)</li> <li>tbl_current.current_id (tbl_current.id = tbl_base.primary_id)</li> </ol> <p>I want to build a left join for <code>tbl_results</code> to <code>tbl_base</code>:</p> <pre><code>SELECT * FROM tbl_base LEFT JOIN tbl_results ON tbl_results.id = tbl_base_id ... </code></pre> <p>What is the most efficient way to construct the query so that I join <code>tbl_results.id</code> to the four possible permutations of ID's present? I tried:</p> <pre><code>SELECT * FROM tbl_base LEFT JOIN tbl_current ON tbl_current.id = tbl_base.id LEFT JOIN tbl_results ON (tbl_results.id = tbl_base.id OR tbl_results.id = tbl_base.primary_id OR tbl_results.id = tbl_current.id OR tbl_results.id = tbl_current.current_id) </code></pre> <p>This doesn't work. The problem is that these tables are large in real life with millions of records and possible connections between all the ID's. I cannot change the structure of the tables in any way - I'm just working with the system I'm given. Any thoughts on how to do this with maximum efficiency? I just want to return any rows in <code>tbl_results</code> where it's ID matches any of the four possible ID's.</p> <p><strong>UPDATE:</strong></p> <p>This is the output I'm after:</p> <pre><code>id value aaaa 10 bbbb NULL cccc 20 dddd 50 --from 'dddd' dddd 10 --from 'zzzz' </code></pre>
    singulars
    1. This table or related slice is empty.
    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.
    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