[英]SQL: Joining data from table with multiple conditions where value matches
表 1 有列 POS、ID、NAME、TYPE 我一直在运行标准查询;
SELECT POS, NAME FROM Table1 WHERE ID = 100 AND TYPE LIKE '%someType%' ORDER BY POS ASC
表 2 有 POS、ID、VALUE、ROLE 列
SELECT POS, VALUE FROM Table2 WHERE IS = 100 AND ROLE LIKE '%someType%' ORDER BY POS ASC
我想将这两者结合起来,以返回具有 3 列的记录集; POS、Table1.NAME 和 Table2.VALUE...无论我尝试使用内部联接做什么,我都会得到比我应该得到的更多的行。 此外,如果 Table 中的相应值不存在,我希望它返回 null 或其他内容,以便记录集本质上看起来像这样;
POS NAME VALUE
1 A DF1
2 B DF1
3 C DF2
4 C null
5 null DF3
etc...
这可能吗?
您似乎正在寻找一个简单的连接。 就像是:
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
请注意,如果您的一个或两个原始查询返回多于一行,您将在结果集中得到这些的笛卡尔积。
或者,如果您想允许来自两个表的行,即使另一个表中没有匹配项,那么您可以full outer join
两个查询,例如:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.