如何针对以下情况进行SQL查询?假设您有两个表:table1和table2,其中table1中的每个条目在table2中可以有多个对应的条目。我想要的查询的伪代码是:
for each $row in table1
$rows = find all rows in table2 that corresponds to $row with $row.id == table2.foreign_id
# $rows is an array of corresponding row in table2
if all rows in $rows meet some condition
then
return $row
else
continue
end
end
编辑:注意在上面的伪代码中,我只希望table1中的行在TABLE2中具有满足某些条件的所有关系,而不仅仅是table1中的某些条件。
PS:我想在SQL中这样做,因为我可能会遇到效率问题。
非常感谢。
答案 0 :(得分:6)
您可以使用where not exists ( .. )
类型子句重新表述。
例如,假装您想要一个订单全部完成的客户列表:
select * from customers c
where not exists (
select * from orders
where customerid=c.id
and status <> 'C'
)
因此,您要求所有没有未完成订单的客户 - 这与订单全部完成的所有客户都是一样的。
而不是:
if all rows in $rows meet some condition
你在说:
if NO rows in $rows DO NOT meet some condition
编辑:正如评论中所指出的,这也将返回没有订单的客户。您可以在上面的末尾添加and exists (select * from orders where customerid=c.id)
以排除这些行。
答案 1 :(得分:4)
select * from table1 as t1
inner join table2 as t2
on t1.id == t2.foreign_id
where -- some condition goes here
此查询仅返回table1中与table2匹配且与where子句匹配的行。
我建议检查SQLCourse - Interactive Online SQL Training for Beginners,因为这确实是一个基本的SQL查询。
答案 2 :(得分:0)
我认为这就是你得到的...嵌套选择是一个名为sub_query的派生表,对应于你伪部分的这一部分($ rows =查找table2中与$ row对应的所有行和$ row .id == table2.foreign_id)。外部选择允许您通过某种条件(if语句)
进一步过滤伪代码的第一部分 select
sub_query.*
from
(select
*
from
table1,
table2
where
table1.id = table2.foreign_key_id) sub_query
where
sub_query.some_field = "some condition"
享受!
答案 3 :(得分:0)
正如ck所提到的,这是非常基本的sql。
表1中的每一行
SELECT table1.* FROM table1
使用$ row.id = $ table2.foreign_id
查找table2中与$ row对应的所有行
LEFT JOIN table2 ON table1.id = table2.foreign_id
如果$ rows中的所有行都满足某些条件
WHERE condition_here
整个SQL变为
SELECT
table1.*
FROM table1
LEFT JOIN table2 ON table1.id = table2.foreign_id
WHERE condition_here
答案 4 :(得分:0)
这是一个可能的解决方案。我使用Oracle,不确定语法是否完全适用于MySQL,但我想你可以使用等效的。
这样做的想法是找到table2中所有行满足所需条件的所有id,然后在table1中查找这些id。
SELECT *
FROM table1
WHERE id IN (
SELECT id
FROM table2
GROUP BY id
HAVING COUNT(*) = SUM( CASE WHEN <somecondition> THEN 1 ELSE 0 END )
)
答案 5 :(得分:-3)
一般格式是:
SELECT *
FROM Table1 t1
INNER JOIN Table2 t2 ON (t1.ID = t2.ID)
WHERE ...