MySQL - SELECTing based on an IF-statement
If I have a MySQL-table consisting of the fields one
, two
, 开发者_如何学编程three
and four
can I then somehow use the IF
statement to receive the field four
, only when a certain condition is true? Do I have to have two sets of SELECT
statement?
Can I do (in pseudocode):
SELECT one, two, three
IF (1 == 1) THEN
four
ENDIF
FROM table
Or do I somehow have to do:
IF (1 == 1) THEN
SELECT one, two, three, four
ENDIF
ELSE THEN
SELECT one, two, three
ENDIF
I'm just curious, I don't have a specific usage for this.
Use:
SELECT t.one,
t.two,
t.three,
CASE WHEN 1 = 1 THEN t.four ELSE NULL END AS four
FROM TABLE t
You can't have optional column(s) in the SELECT list - it either contains the column and an appropriate value, or no column at all.
You can have two (or more) statements separated by an IF statement, but it's not ideal to have an additional column in one of the statements because you are pushing decision logic into your application to handle the missing column situation.
Although there is and IF statement you can use to an extend, you really need stored procedures for this kind of use case.
精彩评论