gpt4 book ai didi

MySQL 一张表内连接 3 个不同的实体表

转载 作者:行者123 更新时间:2023-11-29 02:32:01 25 4
gpt4 key购买 nike

我有 4 个表,Email_Company_Contact_Ref 表是链接了 Email、Company 和 Contact 的表。

**Email_Company_Contact_Ref**

id = primary key
email_id = reference to Email.`id`
ref_id = it can be Company.id / Contact.id
table = reference from which table name

table structure

我尝试使用左连接来获取我的输出,但我得到了重复的结果。如果我尝试 inner join,我根本不会得到任何结果,这是因为 Company 和 Contact 这两个表没有任何共同点。

这是我想要完成的输出。

output result

我可以使用 UNION 来获取输出,但它并不是很有效。我认为这应该是获得输出结果的一种方式。请帮忙。

谢谢!

最佳答案

这是我的mysql答案,希望对你有帮助

SELECT e.email, r.table, c1.name AS company_name, c2.name AS contact_name
FROM email_company_contact_ref r
JOIN email e ON e.id = r.email_id
LEFT JOIN company c1 ON (c1.id = r.ref_id AND r.table = 'company')
LEFT JOIN contact c2 ON (c2.id = r.ref_id AND r.table = 'contact')
GROUP BY r.table, e.email

关于MySQL 一张表内连接 3 个不同的实体表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11681556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com