Given the following table:
type | area | shelf
-----|------|------
1 | a | 5
2 | a | 5
2 | a | 6
1 | a | 7
2 | a | 7
1 | b | 3
An area / shelf combination entry with type 2 always needs a corresponding entry with type 1. Type 1 can exist on its own (eg last row).
How can I find orphan type 2 rows (rows with type 2 without corresponding row with type 1) such as the third row?
Are you looking for this..
SELECT t2.*
FROM yourtable t1
RIGHT JOIN yourtable t2 ON t1.area = t2.area
AND t1.shelf=t2.shelf
AND t1.`type`=1
AND t2.`type`=2
WHERE t1.`type` IS NULL
You can do this with aggregation and a having
clause:
select shelf, area
from t
group by shelf, area
having sum(type = 2) > 0 and -- at least one type 2
sum(type = 1) = 0; -- no type 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.