【发布时间】:2011-03-18 11:42:20
【问题描述】:
我需要做一个 MySQL 查询来显示来自 3 个不同表的数据。
这是表1:
表 1
id
参考
姓名
电子邮件
这是表2:
表 2:
id
电话
这是表3:
表 3:
id
电话
我需要显示 table1 中的所有数据,以及 table2 或 table3 中的电话,前提是 table2 或 table3 中的 id 与 table1 中的参考字段中的数字相同。
有什么建议吗?谢谢!
【问题讨论】:
我需要做一个 MySQL 查询来显示来自 3 个不同表的数据。
这是表1:
表 1
id
参考
姓名
电子邮件
这是表2:
表 2:
id
电话
这是表3:
表 3:
id
电话
我需要显示 table1 中的所有数据,以及 table2 或 table3 中的电话,前提是 table2 或 table3 中的 id 与 table1 中的参考字段中的数字相同。
有什么建议吗?谢谢!
【问题讨论】:
你可以试试
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
看看COALESCE(value,...),也许还有SQL SERVER – Introduction to JOINs – Basic of JOINs
【讨论】:
是的,我有一个建议,修改你的结构。用不同的桌子来存放不同的电话号码是没有意义的。 您可以执行以下操作:
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
编辑:更正联合中的表名
【讨论】:
INNER JOIN而不是LEFT JOIN,因为OP需要显示table1中的所有数据,以及table2或table3中的手机, 仅当 table2 或table3 中的id 与table1 中的引用字段中的编号相同。
table2 和table3 包含具有相同ids 和不同电话号码的行,此解决方案还可以复制table1 行。
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
【讨论】: