我有两张表格相似的表格。 First Table是供应商,其他表是suppliers_contacts。有没有办法将两列合并为一个?
我的suppliers
表格如下:
id | contacts_name | email
-- | ------ | -------
1 | sujith | sujith@sujith
2 | mark |
3 | naveen | naveen@naveen
和supplier_contacts
表,如下所示:
suppliers_id | name | email
-- | ---- |
1 | sujith | sujith1@sujith
2 | user1 | user1@user1
2 | user2 | user2@user2
3 | naveen1 | naveen1@naveen1
3 | naveen | naveen2@naveen
我希望得到这样的东西:
contacts_name | name | email
-- | ------ | -------
sujith | sujith | sujith@sujith
sujith | sujith | sujith1@sujith
user1 | user1 | user1@user1
user2 | user2 | user2@user2
naveen | | naveen@naveen
naveen1 | naveen1 | naveen1@naveen1
naveen | naveen | naveen2@naveen
所有电子邮件ID都应该来自两个表中的一列。
我尝试了以下查询:
SELECT
suppliers.name,
supplier_contacts.name AS name1,
supplier_contacts.email AS sup_c_email
FROM suppliers
JOIN supplier_contacts
ON suppliers.id = supplier_contacts.suppliers_id
任何人都可以帮我这个吗?基本上我希望来自两个表的电子邮件都在一列下,也应该显示两个表中的contacts_name和name。如果任何名称或contacts_name为NULL也很好。
答案 0 :(得分:1)
SELECT suppliers.name, supplier_contacts.name AS name1, supplier_contacts.email AS
sup_c_email
FROM supplier
INNER JOIN suppliers_contacts
ON suppliers.email = supplier_contacts.email
我希望这会对你有所帮助
答案 1 :(得分:0)
答案 2 :(得分:0)
SELECT s.contacts_name,sc.name,sc.email
来自供应商的s
JOIN suppliers_contacts as sc
ON s.id = sc.suppliers_id
如需更多解释,请访问以下链接,希望您能从中获得帮助 https://www.tutorialspoint.com/mysql/mysql-using-joins.htm
答案 3 :(得分:0)
您可以使用union
作为案例,首先获取所有电子邮件的列表然后进行左连接
与suppliers_contacts
select
t.contacts_name,
s.name,
t.email
from (
select contacts_name, email from suppliers where email is not null
union
select name, email from suppliers_contacts
) t
left join suppliers_contacts s on t.email = s.email
order by t.contacts_name;
根据您的上一条评论我期待的结果集是电子邮件列表。它应该合并两个表中的电子邮件列表并显示在一列中,您只需使用union
查询
select contacts_name, email from suppliers where email is not null
union
select name contacts_name, email from suppliers_contacts
order by contacts_name;
编辑 *我想显示两个表中包含每个表的contacts_name和名称的所有电子邮件地址。如果名称为NULL,则为罚款*
select
t.contacts_name,
sc.name supplier_contact_name,
s.contacts_name supplier_name,
t.email
from (
select contacts_name, email from suppliers where email is not null
union
select name, email from suppliers_contacts
) t
left join suppliers_contacts sc on t.email = sc.email
left join suppliers s on t.email = s.email
order by t.contacts_name;