简体   繁体   中英

SQL: Joining data from table with multiple conditions where value matches

Table1 has columns POS, ID, NAME, TYPE I have been running a standard query as so;

SELECT POS, NAME FROM Table1 WHERE ID = 100 AND TYPE LIKE '%someType%' ORDER BY POS ASC

Table2 has columns POS, ID, VALUE, ROLE

SELECT POS, VALUE FROM Table2 WHERE IS = 100 AND ROLE LIKE '%someType%' ORDER BY POS ASC

I would like to combine these two in order to return to a recordset with 3 columns; POS, Table1.NAME, and Table2.VALUE... No matter what I try with inner joins, I keep getting way more rows than I should. Also, if the corresponding value in Table does not exist, I would like it to return a null or something so that essentially a recordset could look like this;

POS    NAME    VALUE
1      A       DF1
2      B       DF1
3      C       DF2
4      C       null
5      null    DF3
etc...

Is this possible at all?

You seem to be looking for a simple join. Something like:

select t1.pos, t1.name, t2.value
from table1 t1
inner join table2 t2 
    on  t2.pos = t1.pos 
    and t2.is = t1.id
    and t2.role like '%someType%'
where
    t1.type like '%someType%'
    and t1.id = 100
order by t1.pos

Please note that, if one or both of your original queries return more than one row, you will get a cartesian products of these in the resultset.

Or if you want to allow rows coming from both tables, even if there is no match in the other table, then you can full outer join both queries, like:

select coalesce(t1.pos, t2.pos) pos, t1.name, t2.value
from (
    select pos, name from table1 where id = 100 and type like '%someType%'
) t1
full outer join (
    select pos, value from table2 where is = 100 and role like '%someType%'
) t2
on t1.pos = t2.pos
order by coalesce(t1.pos, t2.pos)

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