[英]MYSQL select from 3 or more tables
我需要进行MySQL查询以显示3个不同表的数据。
这是表1:
表格1
ID
参考
名称
电子邮件
这是表2:
表2:
ID
电话
这是表3:
表3:
ID
电话
仅当表2或表3中的ID与表1的引用字段中的编号相同时,我才需要显示表1中的所有数据以及表2或表3中的电话。
有什么建议吗? 谢谢!
您可以尝试类似
SELECT t1.*
COALESCE(t2.phone,t3.phone) phone
FROM Table1 t1 LEFT JOIN
Table2 t2 ON t1.reference = t2.id LEFT JOIN
Table3 t3 ON t1.reference = t3.id
是的,我有个建议,请修改您的结构。 拥有不同的表格来容纳不同的电话号码毫无意义。 您可以执行以下操作:
table1( -- you should give it a better name
id,
-- reference, -- not needed now...
name,
email
);
phone_numbers(
id,
table1_id,
phone
);
现在,您可以执行以下操作:
SELECT table1.*, GROUP_CONCAT(phone)
FROM table1
LEFT JOIN phone_numbers ON table1.id = table1_id
GROUP BY table1.id, name, email -- , whatever fields you have more on table1
您要求从table2或table3打电话。
因为这两个表具有公共列,所以我们可以简化整个过程,并通过使用UNION子句将这两个表视为一个单独的表:
select table1.*, v.phone
from table1
inner join (select * from table2
union
select * from table3) v on v.id = table1.reference
编辑:联合中更正的表名称
SELECT t1.*, t2.*, t3.*
FROM table1 t1 JOIN table2 t2
ON t1.reference = t2.ID
JOIN table3 t3
ON t1.reference = t3.ID
我不知道您是否可以在mysql中的select中执行CASE语句,但是您可以尝试将CASE语句作为列并加入。 这是一些sudo代码。
SELECT t1.*, CASE t2.phone IS NOT t3.phone THEN t3.phone ELSE t2.phone END CASE as PhoneNumber
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.reference = t2.id
LEFT JOIN Table3 t3 ON t1.reference = t3.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.