mysql 中的条件连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1255492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
conditional join in mysql
提问by Greg
I have a table id1
, id2
, type
. type
is an enumerated value containing a name of another table.
I'd like to preform a join
with the name of the table of type
.
For example:
我有一个表id1
,id2
,type
。type
是包含另一个表名称的枚举值。我想join
用type
. 例如:
switch($type)
case 'table1':
join table1;
break;
case 'table2':
join table2;
break;
How can I achieve this?
我怎样才能做到这一点?
回答by Greg
You can't do it directly like that... you can do something like this though (not very pretty...):
你不能直接那样做......你可以做这样的事情(不是很漂亮......):
SELECT
t.id,
t.type,
t2.id AS id2,
t3.id AS id3
FROM t
LEFT JOIN t2 ON t2.id = t.id AND t.type = 't2'
LEFT JOIN t3 ON t3.id = t.id AND t.type = 't3'
回答by Steve B.
ugly way:
丑陋的方式:
Table Types, T1, T2:
表类型,T1,T2:
SELECT ... FROM Types, T1 , where Types.ID=T1.Types_ID AND Types.TYPE='TABLE1'
UNION
SELECT ... FROM Types, T2 , where Types.ID=T2.Types_ID AND Types.TYPE='TABLE2'
回答by Ilan
In addition to previous answer: You can combine the two left joins results by using IF statement: IF(t.type= 't2', t2.id, t3.id) as type_id
除了先前的答案:您可以使用 IF 语句组合两个左连接结果: IF(t.type='t2', t2.id, t3.id) as type_id
You can see another mysql conditional joinsexample at mysqldiary.com
您可以在 mysqldiary.com 上看到另一个mysql 条件连接示例