mysql选择1项状态为1.否则选择任何项目

时间:2015-09-08 11:42:46

标签: mysql

我有这样的表:

图片:

| ID | itemID | title  | status | publish |
+----+--------+--------+--------+---------+
|  1 |  251   | title1 |      0 |       1 |
+----+--------+--------+--------+---------+
|  2 |  251   | text   |      0 |       0 |
+----+--------+--------+--------+---------+
|  3 |  251   | text2  |      0 |       1 |
+----+--------+--------+--------+---------+
|  4 |  252   | ttl1   |      1 |       1 |
+----+--------+--------+--------+---------+
|  5 |  252   | blabla |      0 |       1 |

我需要从表中选择一个项目(图像)。 SQL查询如:

SELECT 
    `ID` 
FROM 
    `images` 
WHERE 
    `images`.`itemID` = 251 
    AND
    `status` = 1 OR if no image has status = 1 then select any image
LIMIT 1

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT 
    `ID` 
FROM 
    `images` 
WHERE 
    `images`.`itemID` = 251
ORDER BY `status` DESC
LIMIT 1

如果status值不限于(0, 1),则只需将ORDER BY子句替换为:

ORDER BY CASE WHEN `status` = 1 THEN 0 ELSE 1 END

Demo here

答案 1 :(得分:0)

解决方案比您想象的更容易。只按状态排序,假设它只能是0或1,并且存在所需的itemID

SELECT 
    `ID` 
FROM 
    `images` 
WHERE 
    `images`.`itemID` = 251
ORDER BY
    `status` DESC
LIMIT 1