我在Pinterest风格的应用程序中有2个包含书签和图像的表格。我想创建一个SQL查询,我想根据书签和喜欢选择最流行的图像。
我希望将书签优先于喜欢,但我希望将100张喜欢的图片排名高于带有1个书签的图片。例如,结果如下:
我得到的表格如下:
images_bookmarks
id|id_image|id_user|id_board
images_likes
id|id_image|id_user
所以我想创建一个JOIN,我按照id_image分组的计数排序。我知道如何创建一个连接,但我不确定如何使排序按我所描述的那样运行。
答案 0 :(得分:1)
(左)将您的图像表与您的喜欢/书签表连接,然后为每行分组和计算喜欢和书签。然后按照你给出的标准订购结果(100喜欢"更高"比1书签)
SELECT *, COUNT(b.id) * 100 + COUNT(l.id) AS rank
FROM images i
LEFT JOIN images_bookmarks b
ON i.id = b.image_id
LEFT JOIN images_likes l
ON i.id = l.image_id
GROUP BY i.id
ORDER BY COUNT(b.id) * 100 + COUNT(l.id)
如果您想按书签和喜欢的总和进行排序,但在带有喜欢的图片之前有更多书签的图片,请将ORDER BY子句更改为COUNT(b.id) + COUNT(l.id), COUNT(b.id), COUNT(l.id)
答案 1 :(得分:0)
尝试使用这些表的UNION:
SELECT id_image, NUM_OC (
SELECT id_image, COUNT(id) AS NUM_OC FROM images_bookmarks GROUP BY id_image
UNION
SELECT id_image, COUNT(id) AS NUM_OC FROM images_likes il GROUP BY id_image
)
ORDER BY NUM_OC
只有问题,我会弄清楚,当我的咖啡因开始时,是如何优先考虑上面的书签
答案 2 :(得分:0)
要扩展rurouni88的答案,以下是在出现次数相同时首先对书签进行排序的方法:
SELECT id_image, occurences
FROM (
SELECT id_image, COUNT(id) AS occurences, 2 AS priority
FROM images_bookmarks
GROUP BY id_image
UNION
SELECT id_image, COUNT(id) AS occurences, 1 AS priority
FROM images_likes il
GROUP BY id_image
) AS favorites
ORDER BY occurences DESC, priority DESC
您可以在此处看到它:http://sqlfiddle.com/#!2/eb14f/7