在查询中嵌套'where in'语句

时间:2010-11-22 11:28:03

标签: mysql sql

我有这个SQL查询:


select sum(qty) as 'total' from `sales_flat_quote_item`
where item_id not in (
  select item_id from `sales_flat_quote_item_option`
  where item_id in (
    select item_id from `sales_flat_quote_item`
    where quote_id = 12670
  ) 
  and code = 'is_gift'
)
and quote_id = 12670 and parent_item_id is null

我的任务是使用JOIN子句进行此查询。好查询本身很奇怪。 sales_flat_quote_item用于查询和子查询。这会导致一些有效的问题。

我不是SQL专家,所以我问你。我可以自己处理一小部分嵌套select查询,但我不知道在这种情况下该怎么做。

我们使用Mysql db engine v.5.1


我能够这样做:


select A.qty, A.item_id from `sales_flat_quote_item` as A 
where A.item_id not in 
(
    select B.item_id from 
    `sales_flat_quote_item_option` as B
    inner join `sales_flat_quote_item` as C
    on C.item_id = B.item_id
    where B.code = 'is_gift' and
    C.quote_id = 834
)
and A.quote_id = 834 and A.parent_item_id is null

是否可以在不使用任何子查询的情况下制作它?

1 个答案:

答案 0 :(得分:1)

要解决这个问题,你需要从内到外工作。找出最内部查询返回的内容,然后将该结果与where子句匹配,继续直到达到顶部。

select item_id 
from `sales_flat_quote_item` 
where quote_id = 12670

这将为您提供item_id的列表,其中quote_id为12670。

select item_id 
from `sales_flat_quote_item_option`
where item_id in (Previous Result Set)   
and code = 'is_gift'

这为您提供了item_id的列表,其中item_id包含在上一个列表中,而代码列='is_gift'

select sum(qty) as 'total' 
from `sales_flat_quote_item`     
where item_id not in (Previous Result Set) 
and quote_id = 12670 and parent_item_id is null  

这将返回qty字段的总和,并将其命名为'total',其中item_id不在上一个结果集中,并且quote_id为12670且没有parent_item_id。

这应该足以让你重新制作你的查询,但是如果你仍然有问题发表评论,我会看看是否可以根据上述信息重写它(没有表设计)。