例如我有下表:
id_1 | id_2 | id_3 | name
1 | | | smith
B |AF |2 | waterman
C |3 | | goldman
我想要以下ID的名称('1','AF','C')。输出应该如下所示
id | name
1 | smith
AF | waterman
C | goldman
使用以下代码我可以选择名称,但我不知道如何选择正确的id字段
SELECT name
FROM table
WHERE (id_1 IN ('1', 'AF', 'C')) OR
(id_2 IN ('1', 'AF', 'C')) OR
(id_3 IN ('1', 'AF', 'C'));
谢谢!
答案 0 :(得分:5)
您可以使用CASE
SELECT
(CASE WHEN id_1 IN ('1', 'AF', 'C') THEN id_1
WHEN id_2 IN ('1', 'AF', 'C') THEN id_2
WHEN id_3 IN ('1', 'AF', 'C') THEN id_3
ELSE 0 END ) id
,name
FROM table
WHERE (id_1 IN ('1', 'AF', 'C')) OR
(id_2 IN ('1', 'AF', 'C')) OR
(id_3 IN ('1', 'AF', 'C'));