1

我正在尝试做:

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

4 回答 4

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 演示

于 2013-09-25T14:43:29.367 回答
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
于 2013-09-25T14:43:15.190 回答
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
于 2013-09-25T14:46:31.177 回答
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
;
于 2013-09-26T17:58:38.120 回答