仅显示一致的记录

时间:2015-10-29 02:33:32

标签: mysql

我有这张桌子:

item_number     item        owner_id       status
-----------     ----        --------       ------

12648        Powerbank        5569        returned
657891       Flash drive      5569        returned
6326         Wireless Mouse   5569        sold
987998       Pocket Wifi      8897        sold
78134        Wireless Mouse   7741        sold
7845159      Keyboard         1598        sold
87513        Monitor          1598        sold
9841523      Speakers         8965        returned

我希望结果如下:

item_number     item        owner_id       status
-----------     ----        --------       ------
987998       Pocket Wifi      8897        sold
78134        Wireless Mouse   7741        sold
7845159      Keyboard         1598        sold
87513        Monitor          1598        sold

所以,基本上,我想要的是提取持续销售商品的所有者。一旦用户有退回的项目,他就不应该出现在结果中。

有人可以帮我这个吗?

非常感谢!

1 个答案:

答案 0 :(得分:1)

如果您想要从未返回任何内容的所有者的所有行,请使用not exists子句:

select t.*
from table t
where not exists (select 1
                  from table t2
                  where t2.owner_id = t.owner_id and t2.status <> 'sold'
                 );

如果您只想要一个所有者列表,那么我会使用聚合和having

select owner_id
from table t
group by owner_id
having sum(status <> 'sold') = 0;