MYSQL - Union SELECT& GROUP BY不工作

时间:2014-10-19 18:11:44

标签: mysql database group-by distinct union

我有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

1 个答案:

答案 0 :(得分:0)

尝试使用连接而不是联合

来执行此操作
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';