views:

150

answers:

3

I currently have

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

The problem that I have is that "bid_user" may exist in different rows with different status ( status=1 or status=0). I would like to know if it's possible to select only the * rows where status=0 and where bid_user doesn't doesn't exist with status=1 along with the above conditions(AND email IS NOT NULL GROUP BY bid_user ORDER BY 'bid_price' DESC). I can work around this issue using PHP + 2 mysql queries but it would be much way better to have the exact query in mysql .

A: 

You can do that by replacing "status='0'" condition by "status='0' OR (status='1' AND bid_user IS NULL)"

Rohit
@RJJ can you please explain me the syntax status='0' OR (status='1' AND bid_user IS NULL) ? I'm not sure if I understand correctly but it seems to select the rows that have status=0 or the rows that have status 1 and bid_user "NULL" which is not what I'm looking for .
Michael
+3  A: 

As you want * rows with status='0' AND email IS NOT NULL don't use GROUP BY

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

EDITED (As per comment of @Michael )

Data

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

O/P Required

id  bid_price  bid_user status
3   300        test2      0

SQL Query

   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
Salil
@salil I forgot to add that I use GROUP BY to get records based on unique bid_user
Michael
my question is how to get rows with unique bid_user that have status=0 but also that don't exist with status=1 .
Michael
@Michael:- don't you think bid_user that have status=0 can't have status=1 as you say bid_user is unique and if it has that mean bid_user is not unique
Salil
@Salil In the bidders table i can have a situationlike this: 1) id=1 bid_price=100 bid_user=test status=0 --- 2) id=2 bid_price=200 bid_user=test status=1 --- 3) id=3 bid_price=300 bid_user=tes2 status=0 ---So I need to get the all the rows that have status=0 with bid_user which doesn't exist in rows with status=1. If there exist 2 or more rows eligible with the same bid_user I need to get only one (here I use GROUP BY)
Michael
Using my current syntax I get the first and 3rd row . but as you can see I need to exclude the first row because bid_user=test exist in in a row with status=1
Michael
@Michael:- Check my Edited Answer Hope that helps :)
Salil
A: 

An alternative which is likely to perform better assuming that you have indexes on bid_user and status:

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
Donnie