不能用例并存在于sql语句中

时间:2013-09-25 14:41:17

标签: mysql sql

我正在尝试:

select
case when exists (id) then id else 'n/a' end as id
from mytable
where id="35";

但我有一些错误或另一个弹出。我做错了什么,或者这是不可行的?

check the manual that corresponds to your MySQL server version for the right syntax to use near 'id) then id else 'n/a' end as id from mytable where id="35"' at line 2 */

4 个答案:

答案 0 :(得分:5)

select case when id = 35 then id else 'n/a' end as id
from mytable
order by case when id = 35 then 1 else 2 end 
limit 1

SQLFiddle demo

答案 1 :(得分:2)

这是一个小技巧,

SELECT  COALESCE(b.id, 'n/a') id
FROM    
        (
            SELECT 35 id -- the id you want to search
        ) a
        LEFT JOIN mytable b
            ON a.id = b.id
WHERE   a.id = 35

答案 2 :(得分:2)

使用这样的子查询:

SELECT 
  TABEL1.Id, 
  CASE WHEN EXISTS (SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABLE1.ID)
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1

答案 3 :(得分:0)

如果所有id值都是唯一的:

SELECT
  COALESCE(
    (SELECT id FROM mytable WHERE id = 35),
    'n/a'
  ) AS id
;

如果列可以有重复项,只需将LIMIT 1添加到子查询的末尾:

SELECT
  COALESCE(
    (SELECT id FROM mytable WHERE id = 35 LIMIT 1),
    'n/a'
  ) AS id
;