根据关系将两个表连接在一个辅助表中

时间:2018-06-11 12:52:10

标签: mysql

我有两张桌子

用户:phone_number,优惠券

客户:customer_id,优惠券

我想创建一个帮助表,根据特定的优惠券将用户和customer_id链接在一起。第三个表将有三个字段:coupon,phone_number,customer_id,应该从这两个表中检索。我尝试了内部加入,但似乎不起作用。有人可以帮忙吗?

SELECT customers.customer_id as customer_id, users.phone as 
phone
FROM linked_customers_users 
INNER JOIN customers
ON linked_customers_users.customer_id = customers.customer_id
INNER JOIN users
ON linked_customers_users.phone = users.phone

2 个答案:

答案 0 :(得分:2)

尝试LEFT JOIN

SELECT customers.customer_id as customer_id, users.phone as 
phone
FROM linked_customers_users 
LEFT JOIN customers
ON linked_customers_users.customer_id = customers.customer_id
LEFT JOIN users
ON linked_customers_users.phone = users.phone

答案 1 :(得分:1)

道歉作为评论者指出你正在使用mysql。您可以随时尝试模拟完整的外部联接(请注意,如果您拥有它们,将删除重复项):

SELECT * FROM linked_customers_users 
LEFT JOIN users ON linked_customers_users.coupon = users.coupon
UNION
SELECT * FROM linked_customers_users 
RIGHT JOIN users ON linked_customers_users.coupon = users.coupon