我有一个SELECT语句,它使用LEFT JOIN从我的数据库中的不同表中获取各种字段。我只想在满足某个条件时选择其他字段。这是我尝试实现的一个例子。
boolean return_flag = list_name.contains(var_name)
if return_flag{
//do stuff
}
为了澄清,上面的例子已经完全弥补了,但它展示了我尝试做的事情。我知道' IF'中间的陈述是完全错误的 - 这是我需要帮助的一点。我查看了MySQL IF语句和MySQL IF函数,但无法弄清楚它应该如何工作。
任何帮助都非常感激。
谢谢!
答案 0 :(得分:1)
IF
子句喜欢这个;)
SELECT table1.useriD,
table1.name,
table2.address,
table2.employed,
IF(table2.employed = 1, table3.jobTitle, null) AS additionalCol
FROM table1
LEFT JOIN table2 ON table1.userID = table2.userID
LEFT JOIN table3 ON table2.userID = table3.userID
您也可以使用CASE WHEN
:
SELECT table1.useriD,
table1.name,
table2.address,
table2.employed,
CASE WHEN table2.employed = 1 THEN table3.jobTitle ELSE null END AS additionalCol
FROM table1
LEFT JOIN table2 ON table1.userID = table2.userID
LEFT JOIN table3 ON table2.userID = table3.userID
答案 1 :(得分:0)
SELECT table1.useriD,
table1.name,
table2.address,
table2.employed,
(IF table2.employed = 1, table3.jobTitle, null) as JobTitle
FROM table1
LEFT JOIN table2 ON table1.userID = table2.userID
LEFT JOIN table3 ON table2.userID = table3.userID
参考:http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html
答案 2 :(得分:0)
你的if条件应该如下
SELECT table1.useriD,
table1.name,
table2.address,
table2.employed,
(IF table2.employed = 1, table3.jobTitle, null) as jobTitle
FROM table1
LEFT JOIN table2 ON table1.userID = table2.userID
LEFT JOIN table3 ON table2.userID = table3.userID