MySQL INNER JOIN首先按多个匹配排序

时间:2014-04-07 11:01:29

标签: php mysql sql

我有以下表格

gifts - a list of products
tags - a list of tags that can be applied to products
tags_gifts - a join for gifts and tags if they are applicable

这是两个标签示例(id,name):

508 - jewellery
7 - gold

我有以下SQL结果:

SELECT * FROM gifts 
LEFT JOIN tags_gifts ON tags_gifts.gift_id = gifts.gift_id 
INNER JOIN tags ON tags.id = tags_gifts.tag_id 
WHERE published = '1' AND ( (tags_gifts.tag_id = '508' OR tags_gifts.tag_id = '7') ) 
GROUP BY gifts.gift_id 
ORDER BY gift_popularity DESC LIMIT 0,20 

这样可以正常使用'珠宝'或'黄金'的比赛显示所有结果并按人气排序,但我想首先展示多个比赛,例如。产品与两个标签匹配,然后按受欢迎程度对其余产品进行排序。

无法弄清楚如何做到这一点 - 谢谢

2 个答案:

答案 0 :(得分:4)

您可以在COUNT()中使用ORDER BY,因此如果count返回2,则表示产品同时包含两个标记

SELECT * FROM gifts 
LEFT JOIN tags_gifts ON tags_gifts.gift_id = gifts.gift_id 
INNER JOIN tags ON tags.id = tags_gifts.tag_id 
WHERE published = '1' AND ( (tags_gifts.tag_id = '508' OR tags_gifts.tag_id = '7') ) 
GROUP BY gifts.gift_id 
ORDER BY COUNT(*) DESC , gift_popularity DESC
 LIMIT 0,20

答案 1 :(得分:0)

这将起作用并且速度很快,你可以调整"极限20 OFFSET 0"如你所愿。

SELECT a.* FROM (
    SELECT * FROM gifts 
    LEFT JOIN tags_gifts ON tags_gifts.gift_id = gifts.gift_id 
    INNER JOIN tags ON tags.id = tags_gifts.tag_id 
    WHERE published = '1' AND ( (tags_gifts.tag_id = '508' AND tags_gifts.tag_id = '7')  ) 
    GROUP BY gifts.gift_id 
    ORDER BY gift_popularity DESC  
)  UNION (
    SELECT * FROM gifts 
    LEFT JOIN tags_gifts ON tags_gifts.gift_id = gifts.gift_id 
    INNER JOIN tags ON tags.id = tags_gifts.tag_id 
    WHERE published = '1' AND ( (tags_gifts.tag_id = '508' OR tags_gifts.tag_id = '7') ) 
    GROUP BY gifts.gift_id 
    ORDER BY gift_popularity DESC
) a LIMIT 0,20