mysql查询 - 选择具有特定值的distinct值,group by

时间:2010-07-10 03:41:11

标签: sql mysql group-by aggregate-functions

我目前有

SELECT * FROM bidders 
WHERE status='0' 
AND email IS NOT NULL 
GROUP BY `bid_user` 
ORDER BY 'bid_price' DESC

我遇到的问题是“bid_user”可能存在于具有不同状态的不同行中(status = 1或status = 0)。   我想知道是否可以只选择status = 0的*行以及bid_user不存在且status = 1以及上述条件(AND email IS NOT NULL) GROUP BY bid_user 订购'bid_price'DESC)。    我可以使用PHP + 2 mysql查询解决这个问题,但在mysql中获得确切的查询会好得多。

3 个答案:

答案 0 :(得分:3)

如您所愿* status='0'email IS NOT NULL的行不使用GROUP BY

SELECT * FROM bidders 
WHERE status='0' 
AND email IS NOT NULL 
ORDER BY 'bid_price' DESC

已编辑(根据@Michael的评论)

数据

id  bid_price  bid_user status
1   100        test      0
2   200        test      1
3   300        test2     0

需要O / P

id  bid_price  bid_user status
3   300        test2      0

SQL查询

   SELECT * FROM bidders 
     WHERE bid_user NOT IN (select DISTINCT `bid_user` FROM `bidders` where status='1') 
       AND email IS NOT NULL 
     ORDER BY 'bid_price' DESC

答案 1 :(得分:0)

您可以通过将“status ='0'”条件替换为“status ='0'OR(status ='1'AND bid_user IS NULL)”

来实现。

答案 2 :(得分:0)

假设您在bid_userstatus上有索引,可能会有更好的替代方案:

SELECT 
  b.* 
FROM 
  bidders b
WHERE 
  status='0' 
  AND email IS NOT NULL 
  AND not exists (
    select 1 from bidders bx where bx.status='1' and bx.bid_user = b.bid_user
  )
ORDER BY 'bid_price' DESC