[英]'IF' in 'FROM' statement - choose table value based on column value
SELECT CI FROM users WHERE something;
IF users.CI='pc' THEN
SELECT name FROM table1 WHERE something;
ELSE IF users.CI='ph' THEN
SELECT name FROM table2 WHERE something;
END IF
I know that doesn't work, but is an example to understand. 我知道这行不通,但是这是一个可以理解的示例。
It's possible all of this in one query ? 所有这些都可能在一个查询中完成?
SET @var = (SELECT CI FROM users WHERE something);
SELECT
CASE @var
WHEN 'pc' THEN
(SELECT name FROM table1 WHERE something)
WHEN 'ph' THEN
(SELECT name FROM table2 WHERE something)
END;
You cannot use IF ... THEN
in a SQL query. 您不能在SQL查询中使用
IF ... THEN
。
The solution is to left outer join both tables, letting the optimizer choose which table will be used by specifying so in the ON
clauses. 解决方案是左连接两个表,让优化器通过在
ON
子句中指定so来选择使用哪个表。
You didn't explain what "something" was, so in this example, I am going to assume that "users" has an "id" column and that table1 and table2 have a "user_id" column, and that you are interested in the user with id = 1. 您没有解释什么是“东西”,因此在此示例中,我将假设“用户”具有“ id”列,而table1和table2具有“ user_id”列,并且您对ID = 1的用户。
SELECT COALESCE(t1.name,t2.name) AS name
FROM users u
LEFT JOIN table1 t1 ON u.CI = 'pc' AND t1.user_id = u.id
LEFT JOIN table2 t2 ON u.CI = 'ph' AND t2.user_id = u.id
WHERE u.id = 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.