在MySQL中获取最近的用户喜欢

时间:2018-05-03 08:29:34

标签: mysql

我有一个用户喜欢的产品的网站,我需要为每个产品显示最近10个用户的列表,这些用户最近喜欢在desc 创建的订购的产品及其头像。我试图找到一种有效的方法来做到这一点,请注意,一个产品可以有1000个喜欢,并且要高效我只想展示最后10个喜欢。

我有两张桌子

产品

id, title, ....

喜欢

id, user_id, product_id, created_at

我想最多吸引10位最近喜欢该产品的用户ID。从那里我将对用户ID进行另一个查询以获取他们的名字和头像,但是如何进行第一次查询以获取每个产品的用户ID?

所以结果应该是

product_id, liked by
1           12,23,45,67
2           13,4,5
3           1

etc

1 个答案:

答案 0 :(得分:1)

您是否尝试过运行此查询:

SELECT p.id AS product_id, u.username, u.avatar, u.id AS user_id FROM products AS p 
LEFT JOIN likes AS l ON l.produc_id = p.product_id
LEFT JOIN users AS u ON u.id = l.user_id
WHERE p.id = {PRODUCT_ID} -- If you want it for a single product
ORDER BY l.created_at DESC
LIMIT 10

这将在一个查询中返回10个用户名及其产品的头像列表。

您可能需要调整此查询,因为您没有提供表格及其关系的详细说明。

编辑:

根据请求添加另一个sql示例:

SELECT l.product_id, p.name AS product_name, GROUP_CONCAT(l.user_id) AS listOfUsers, GROUP_CONCAT(u.username) AS username, GROUP_CONCAT(u.avatar) AS avatars  FROM likes AS l
LEFT JOIN products AS p ON p.id = l.product_id
LEFT JOIN users AS u ON u.id = l.user_id
WHERE l.product_id IN(1,2,3)
ORDER BY l.created_at DESC
LIMIT 10

这应该返回类似

的内容
product_id | listOfUsers | usernames          | avatars
1          |  1,2,3      |  test1,test2,test3 |  img1, img2, img3
2          |  4,5,6      |  test4,test5,test6 |  img4, img5, img6

编辑#2:

我认为这是您要查找的查询:

SELECT p.id, GROUP_CONCAT(l.user_id) As userList, GROUP_CONCAT(l.username) AS usernameList, GROUP_CONCAT(l.avatar) AS avatarList
FROM products AS p
LEFT JOIN ( 
    SELECT l.product_id, l.user_id, u.username, u.avatar
    FROM likes AS l
    LEFT JOIN users AS u ON u.id = l.user_id
    ORDER BY l.created_at DESC 
    LIMIT 10
) 
AS l ON l.product_id = p.id
WHERE p.id IN (1,2,3)
GROUP BY p.id