我正在尝试列出唯一user engagements
的engagement_type
我曾经有以下查询。
SELECT u.id, u.fname, u.lname FROM (
SELECT id, engagement_type FROM (
SELECT user_id AS id, 'comment'
FROM comments WHERE commentable_id = 48136 AND commentable_type = 'Video'
UNION ALL
SELECT user_id AS id, 'like'
FROM likes WHERE likeable_id = 48136 AND likeable_type = 'Video'
) AS a
GROUP BY id
LIMIT 10
) b JOIN users u USING (id);
回报:
id | fname | lname
------------------------------
1 | joe | abc
2 | sarah | qer
3 | megan | tryey
4 | john | vdfa
这很好。现在,我想包括参与类型。我想出了这个:
SELECT u.id, u.fname, u.lname, engagement_type FROM (
SELECT id, engagement_type FROM (
SELECT user_id AS id, 'comment' AS engagement_type
FROM comments WHERE commentable_id = 48136 AND commentable_type = 'Video'
UNION ALL
SELECT user_id AS id, 'like' AS engagement_type FROM likes
WHERE likeable_id = 48136 AND likeable_type = 'Video'
) AS a
GROUP BY id, engagement_type
LIMIT 10
) b JOIN users u USING (id);
现在返回:
id | fname | lname | engagement_type
---------------------------------------------------
1 | joe | abc | comment
2 | sarah | qer | like
3 | megan | tryey | like
4 | john | vdfa | like
1 | joe | abc | like
3 | megan | tryey | comment
上面的唯一问题。结果不再是唯一的。如您所见,Joe 和 Megan 有 2 个条目。
知道我怎样才能让它工作吗?