gpt4 book ai didi

mysql - 查询中嵌套 'where in' 语句

转载 作者:行者123 更新时间:2023-11-29 14:57:24 24 4
gpt4 key购买 nike

我有这个 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 数据库引擎 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

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

最佳答案

要解决这个问题,您需要从内到外进行工作。找出最里面的查询返回的内容,然后将该结果与 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。

这应该足以让您重新设计查询,但如果您仍然遇到问题,请给我发表评论,我会看看是否可以根据上述信息重写它(无表格设计)。

关于mysql - 查询中嵌套 'where in' 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4244930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com