SQL 只显示一个订单行的订单。如果更多行不显示任何内容
SQL only show orders with one order row. if more rows don display anything
我正在尝试搜索订单行中包含一篇特定文章的订单,但如果有不止一行,我不想看到任何行。
这是两个订单的示例,我只想获得一个结果。订单9891026有两行,9891025只有一行。
select order_no, line_no
from customer_order_line
where order_no in('9891026','9891025')
结果
order_no
line_no
9891026
1
9891026
2
9891025
1
我只想得到
order_no
line_no
9891025
1
我不知道如何对此进行正确的查询。
一种方法是检查订单 exists
的 line_no 是否大于 1:
select ol.order_no, ol.line_no
from customer_order_line ol
where ol.order_no in (9891026, 9891025)
and not exists (
select * from customer_order_line x
where x.order_no = ol.order_no and x.line_no > 1
);
或者,您可以执行 GROUP BY
并使用 HAVING
确保只有一行。
select ol.order_no, min(ol.line_no)
from customer_order_line ol
where ol.order_no in ('9891026', '9891025')
group by ol.order_no
having count(*) = 1
首先查找单行订单号 order_no
(子查询),然后仅从具有这些订单号的订单中查找 select。请注意,连接查询(虽然可能更难阅读)可能更有效。
select *
from customer_order_line
where order_no in
(
select order_no
from customer_order_line
group by order_no
having count(*) = 1
) -- this is the list of single-item orders
and order_no in (9891026,9891025) -- this is the list of target orders
我正在尝试搜索订单行中包含一篇特定文章的订单,但如果有不止一行,我不想看到任何行。
这是两个订单的示例,我只想获得一个结果。订单9891026有两行,9891025只有一行。
select order_no, line_no
from customer_order_line
where order_no in('9891026','9891025')
结果
order_no | line_no |
---|---|
9891026 | 1 |
9891026 | 2 |
9891025 | 1 |
我只想得到
order_no | line_no |
---|---|
9891025 | 1 |
我不知道如何对此进行正确的查询。
一种方法是检查订单 exists
的 line_no 是否大于 1:
select ol.order_no, ol.line_no
from customer_order_line ol
where ol.order_no in (9891026, 9891025)
and not exists (
select * from customer_order_line x
where x.order_no = ol.order_no and x.line_no > 1
);
或者,您可以执行 GROUP BY
并使用 HAVING
确保只有一行。
select ol.order_no, min(ol.line_no)
from customer_order_line ol
where ol.order_no in ('9891026', '9891025')
group by ol.order_no
having count(*) = 1
首先查找单行订单号 order_no
(子查询),然后仅从具有这些订单号的订单中查找 select。请注意,连接查询(虽然可能更难阅读)可能更有效。
select *
from customer_order_line
where order_no in
(
select order_no
from customer_order_line
group by order_no
having count(*) = 1
) -- this is the list of single-item orders
and order_no in (9891026,9891025) -- this is the list of target orders