简体   繁体   中英

MySQL: Get data from multiple tables allowing nulls with a list of ids

I got this tables that look like this:

table 1

|id|value1|value2|value3

table 2

|id|value4|value5|value6

The id value in each table is unique but an id could appear in a table 1 but no in table 2. (value 1 is equal to value4 but if id dont appear in table 2 value4 would be null... )

Then I got this a of ids and I want to get sometime like (supossing that id appear in table 1 but no in 2 and vice versa):


resultgrid
| id | value1| value2| value3|value4|value5|value6

|838383|result1|result2|result3|null  |null  |null
|548438|null   |null   |null   |result4|result5|result6

hope you guys can help me, thanks!

EDIT: query i've been trying (it's actually a set of collected pieces of answer i'd see in stack overflow)

SELECT t1.*, t2.value4, t2.value5, t2.value6
FROM table1 as t1
JOIN table2 AS t2 ON t2.id = t1.id
Where t1.id = t2.id = 838383

this get me 0 rows returned.

I want to make it general to use the <2000 id list.

  • You can use two different Select queries, using Left join between the two tables. In the first query, consider table1 as leftmost table; and table2 as leftmost in the second query.
  • Use Where <right table id> IS NULL to filter out rows where there is no matching entry in the rightmost table.
  • Use Union to combine the resultset. Since there will not be any duplicates (due to our query results), we can use Union All .

Try the following:

SELECT t1.id, t1.value1, t1.value2, t1.value3, 
              t2.value4, t2.value5, t2.value6 
FROM table1 AS t1 
LEFT JOIN table2 AS t2 ON t2.id = t1.id 
WHERE t2.id IS NULL 

UNION ALL 

SELECT t2.id, t1.value1, t1.value2, t1.value3, 
              t2.value4, t2.value5, t2.value6 
FROM table2 AS t2 
LEFT JOIN table1 AS t1 ON t1.id = t2.id 
WHERE t1.id IS NULL 

You want a full outer join which MySQL does not support. In your case, you can emulate this with left join :

select t1.*, t2.value4, t2.value5, t2.value6
from (select 838383 as id
     ) i left join
     table1 t1
     on t1.id = i.id left join
     table2 t2 
     on t2.id = i.id;

The list of ids you want to keep goes in the i subquery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM