在mysql中获得最近的用户喜欢

bkhjykvo  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(273)

我有一个网站,在那里用户喜欢的产品,我需要为每个产品显示多达10个用户谁最近喜欢的产品在desc和他们的头像创建订单列表。我正试图找到一个有效的方法来做到这一点,注意一个产品可以有1000的喜欢,而要有效率,我只想显示最后10喜欢。
我有两张table
产品

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
yyyllmsg

yyyllmsg1#

您是否尝试运行此查询:

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

相关问题