我有两张电子邮件和电话号码存储表。这两个表的列shop
都引用了shop_id
。
我想要的是从id = 1的商店中取出所有电子邮件,然后从同一商店获取电话号码。
SELECT
shop_contact_phone.id,
shop_contact_phone.shop_id,
number, tbl.email
FROM (
SELECT *
FROM shop_contact_email
WHERE shop_id = 1
) AS tbl
JOIN
shop_contact_phone
ON (shop_contact_phone.shop_id = tbl.shop_id);
但是,我收到了重复的条目。我在这做错了什么?
这是我的sqlfiddle。
答案 0 :(得分:1)
如果您想要电话号码和电子邮件的列表,请使用union all
代替join
:
select sce.shop_id, 'email' as contacttype, sce.email
from shop_contact_email sce
where sce.shop_id = 1
union all
select scp.shop_id, 'phone', scp.number
from shop_contact_phone scp
where scp.shop_id = 1;
这会将它们放在不同的行上。您也可以根据需要将它们聚合成字符串或数组。