SELECT login.id_user
, username
, SUBSTRING_INDEX
( GROUP_CONCAT
( DISTINCT id_item
ORDER
BY items.ts_created
),",",3
) grouped_items
FROM login
, items
WHERE login.username LIKE '%%'
AND items.id_user = login.id_user
AND login.ts_deleted IS NULL
AND items.ts_deleted IS NULL
GROUP
BY login.id_user
ORDER
BY login.ts_created DESC
id喜欢从登录表中获取条目表中没有项目的条目。现在我写的查询抓住了3个最近的项目的用户。
我有这个抓取所有用户的查询。所以我想我试图将两个查询合并为一个。
SELECT id_user,username
FROM login
WHERE login.ts_deleted IS NULL
ORDER BY ts_created DESC
答案 0 :(得分:1)
如果您想要所有用户,则需要left join
并且要非常小心on
子句:
SELECT l.id_user, l.username,
SUBSTRING_INDEX(GROUP_CONCAT(DISTINCT i.id_item ORDER BY i.items.ts_created), ',', 3) as grouped_items
FROM login l LEFT JOIN
items i
ON i..id_user = l.id_user and i.ts_deleted IS NULL
WHERE l.username LIKE '%%'
l.ts_deleted IS NULL
GROUP BY l.id_user
ORDER BY l.ts_created DESC