如何针对以下情况进行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
Run Code Online (Sandbox Code Playgroud)
编辑:注意在上面的伪代码中,我只希望table1中的行在TABLE2中具有满足某些条件的所有关系,而不仅仅是table1中的某些条件.
PS:我想在SQL中这样做,因为我可能会遇到效率问题.
非常感谢.
您可以使用where not exists ( .. )类型子句重新构造它.
例如,假装您需要一个订单全部完成的客户列表:
select * from customers c
where not exists (
select * from orders
where customerid=c.id
and status <> 'C'
)
Run Code Online (Sandbox Code Playgroud)
因此,您要求所有没有未完成订单的客户 - 这与所有订单全部完成的客户都是一样的.
代替:
if all rows in $rows meet some condition
Run Code Online (Sandbox Code Playgroud)
你是说:
if NO rows in $rows DO NOT meet some condition
Run Code Online (Sandbox Code Playgroud)
编辑:正如评论中所指出的,这也将返回没有订单的客户.您可以添加and exists (select * from orders where customerid=c.id)到上面的末尾以排除这些行.
| 归档时间: |
|
| 查看次数: |
297 次 |
| 最近记录: |