简体   繁体   中英

mysql select from where a condition is met

My table structure is as follows

ProductID |  Image  | Default
1            1.jpg     N
1            2.jpg     Y
1            3.jpg     N
2            4.jpg     N
2            5.jpg     N
3            6.jpg     Y
3            7.jpg     N

I'm Trying to get a return of all producID where there is no default image 'N' , eg the above should return productID 2. Sorry no code attempt , as i'm not sure what to do at all.

Group by the product and select only those having none default=Y

select productID
from your_table
group by productID
having sum(`default` = 'Y') = 0

Try this:

SELECT t1.productID
FROM yourtable t1
WHERE NOT EXISTS(
    SELECT 'DEFAULT'
    FROM yourtable t2
    WHERE T2.productid = t1.productid
    AND T2.`default` = 'Y'
)
This SQL code does what you want:

SELECT productID FROM  
    (SELECT productID, SUM(table.default = 'Y') AS Y_count 
    FROM table
    GROUP BY productID) AS tbl
WHERE Y_count = 0

如果default是数据库中的一列,则可以使用:

Select * from mytabale where 'Default'='Y'

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM