MySQL: SELECT inside SELECT IF()语句。

时间:2022-10-09 20:17:16

Can I have something like this?

我能要这样的东西吗?

SELECT IF((SELECT COUNT(id) FROM table WHERE id = 1) = 0, 1, <nothing_to_happen>) AS Available

My goal is select this:

我的目标是选择这个:

+---------+
|Available|
+---------+
|1        |
+---------+

Only if there is no row selected from this query:

只有在这个查询中没有选择行时:

SELECT id FROM table WHERE id = 1

If the row with id = 1 exists in table, I want my query to return zero rows! Is that possible?

如果表中存在id = 1的行,我希望查询返回零行!这有可能吗?

2 个解决方案

#1


5  

SELECT  1
FROM    dual
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    mytable
        WHERE   id = 1
        )

#2


0  

Query:

查询:

SELECT CASE
           WHEN COUNT(id) = 0 THEN 1
           ELSE 0
       END AS Available
FROM `TABLE`
WHERE id = 1

#1


5  

SELECT  1
FROM    dual
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    mytable
        WHERE   id = 1
        )

#2


0  

Query:

查询:

SELECT CASE
           WHEN COUNT(id) = 0 THEN 1
           ELSE 0
       END AS Available
FROM `TABLE`
WHERE id = 1