在此查询中是否有条件选择表格列?
SELECT x,y FROM Z
我想选择Y列Y条件,如:
SELECT x ( ONLY WHERE x_type = '20' ), y FROM Z # just example of what i am trying to do :)
y_type是另一列,它的值是选择是否取决于Y的原因!是否有可能做到这一点,或者我只是打错了门?
答案 0 :(得分:2)
不,这是不可能的。但是,如果不满足条件,则可以将列设置为NULL:
SELECT IF (x_type = 20, x, NULL) AS x
y
FROM Z
答案 1 :(得分:1)
select case when x_type = '20' then
x else '' end,y from z
答案 2 :(得分:1)
不确定细节:
SELECT x
, CASE WHEN x_type = '20' THEN y
ELSE NULL
END AS y
FROM Z
或者你想要简单:
SELECT x
, y
FROM Z
WHERE x_type = '20'
答案 3 :(得分:1)
如果要在x_type上选择,则SQL查询应为
SELECT x, y FROM Z where x_type = '20'
如果您想约束y_type,那么您可能希望将OR y_type = 'nn'
添加到结尾。我想你的问题是你是否需要在select子句和where子句中都有相同的列。答案是“不,你没必要。”
答案 4 :(得分:1)
SELECT CASE WHEN y_type = 20 THEN y ELSE NULL END As y -- replace y_type with column to check
,.... -- other column list
FROM yourtable
您还可以将带有IN的CASE用于多个值,例如
SELECT CASE WHEN y_type IN (10,20) THEN y ELSE NULL END As y -- replace y_type with column to check
,.... -- other column list
FROM yourtable