我有3个表,日志,成员和访客,但我的日志仅存储为客户(用户)的ID,即他们的guest_id或member_id。这就是问题所在,因为它们来自不同的表,所以我不确定如何将其数据组合在一起。
checkout_log表
id user_id checkout_as
--------------------------------------
1 1 member
2 2 guest
会员表
id fullname
--------------------------------------
1 member01
2 member02
客人桌
id fullname
--------------------------------------
1 guest01
2 guest02
我想要达到的目标-结果
id user_id fullname checkout_as
----------------------------------------------
1 1 member01 member
2 2 guest02 guest
曾尝试使用UNION ALL或GROUP BY遵循以下sql语句,但没有运气。
SELECT * FROM
(
SELECT checkout_log.id,checkout_log.user_id,guests.fullname,guests.email,checkout_log.checkout_as
FROM checkout_log
LEFT JOIN checkout_product ON checkout_product.checkout_log_id = checkout_log.id
LEFT JOIN guests ON checkout_log.user_id = guests.id
UNION ALL
SELECT checkout_log.id,checkout_log.user_id,members.fullname,members.email,checkout_log.checkout_as
FROM checkout_log
LEFT JOIN checkout_product ON checkout_product.checkout_log_id = checkout_log.id
LEFT JOIN members ON checkout_log.user_id = members.id
) derivedTable
GROUP BY id
最佳答案
尝试使用联接而不是联合来做到这一点
select cl.id, cl.user_id,
coalesce(m.fullname, g.fullname) as fullname,
cl.checkout_as
from checkout_log cl left join
members m
on cl.user_id = m.id and cl.checkout_as = 'member' left join
guests g
on cl.user_id = g.id and cl.checkout_as = 'guest';
关于mysql - MYSQL-联合选择和GROUP BY无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26453778/