[英]MySQL JOIN: Only return rows where all values from right table are NULL
I have two MySQL tables like this:我有两个这样的 MySQL 表:
orders:
+----------+------+
| order_id | name |
+----------+------+
| 1 | Mary |
| 2 | John |
| 3 | Anne |
+----------+------+
order_details:
+----------+----------------+
| order_id | shipped |
+----------+----------------+
| 1 | null |
| 1 | null |
| 1 | SHIPPED-123ABC |
| 2 | null |
| 2 | null |
| 3 | SHIPPED-XYZ |
| 3 | SHIPPED-XYZ |
| 3 | null |
+----------+----------------+
Now I want to join the order_details-table to the orders-table but only show the entries that only have NULL shipped values in the order_details table.现在我想将 order_details-table 加入到 orders-table 但只显示 order_details 表中只有 NULL 运输值的条目。 So in this example only order_id #2 would get returned.
所以在这个例子中,只有 order_id #2 会被返回。
So the result would be:所以结果将是:
+----------+------+---------+
| order_id | name | shipped |
+----------+------+---------+
| 2 | John | null |
+----------+------+---------+
Thank you!谢谢!
You can use not exists
:您可以使用
not exists
:
select o.order_id, o.name, null as shipped
from orders o
where not exists (select 1
from order_details od
where od.order_id = o.order_id and od.shipped is not null
);
Simple aggregation with JOIN
would also work :使用
JOIN
简单聚合也可以:
select o.order_id, o.name, null as shipped
from orders o inner join
order_details od
on od.order_id = o.order_id
group by o.order_id, o.name
having min(od.shipped) = max(od.shipped) and min(od.shipped) is null;
If you want orders that have at least one row in order_details
, then use aggregation:如果您想要在
order_details
中至少有一行的订单,请使用聚合:
select o.*
from (select od.order_id
from order_details
group by od.order_id
having count(shipped) = 0
) od join
orders o
on od.order_id = o.order_id;
If you want all such orders, even those with no rows in order_details
, then use not exists
:如果你想要所有这样的订单,即使是那些在
order_details
没有行的订单,那么使用not exists
:
select o.*
from orders o
where not exists (select 1
from order_details od
where od.order_id = o.order_id and
od.shipping is not null
);
Check whether below query gives what you want.检查以下查询是否提供您想要的。
SELECT
o.order_id,
o.name,
od.shipped
FROM
orders o
INNER JOIN order_details od ON od.order_id = o.order_id
WHERE
od.shipped IS NULL
AND od.shipped NOT IN
(
SELECT od.shipped
WHERE
od.shipped IS NOT NULL
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.