MySQL - 基于IF语句进行选择

时间:2022-04-24 09:08:10

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?

如果我有一个包含字段1,2,3和4的MySQL表,那么我可以以某种方式使用IF语句来接收字段4,只有当某个条件为真时?我必须有两组SELECT语句吗?

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.

我只是很好奇,我没有具体用法。

2 个解决方案

#1


4  

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.

SELECT列表中不能包含可选列 - 它包含列和适当的值,或者根本没有列。

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.

您可以使用IF语句分隔两个(或更多)语句,但是在其中一个语句中有一个额外的列并不理想,因为您正在将决策逻辑推入应用程序以处理丢失的列情况。

#2


0  

Although there is and IF statement you can use to an extend, you really need stored procedures for this kind of use case.

尽管您可以使用和IF语句进行扩展,但您确实需要这种用例的存储过程。

#1


4  

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.

SELECT列表中不能包含可选列 - 它包含列和适当的值,或者根本没有列。

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.

您可以使用IF语句分隔两个(或更多)语句,但是在其中一个语句中有一个额外的列并不理想,因为您正在将决策逻辑推入应用程序以处理丢失的列情况。

#2


0  

Although there is and IF statement you can use to an extend, you really need stored procedures for this kind of use case.

尽管您可以使用和IF语句进行扩展,但您确实需要这种用例的存储过程。