在mysql中对分组行进行排序

时间:2013-02-12 19:45:03

标签: mysql group-by sql-order-by

SELECT t1.item_id, t1.item, t1.created, t1.owner, t1.type, t1.fld, t2.tag
FROM items AS t1
INNER JOIN tagged AS t2 ON t1.item_id = t2.item_id
WHERE tag
IN ('how', 'jkas', 'bodor', 'zimp', 'ctuo', 'sjex', 'kek'
)
GROUP BY item_id
ORDER BY t1.created DESC 
LIMIT 0 , 100

如何根据他们与IN TAG的匹配数量来订购商品?我的手册非常深入,我找不到答案,我迷失了我不理解的东西。

1 个答案:

答案 0 :(得分:1)

您可以使用COUNT并将结果放在子查询中:

SELECT * 
FROM (
   SELECT t1.item_id, t1.item, t1.created, t1.owner, 
      t1.type, t1.fld, t2.tag, COUNT(DISTINCT t2.tag) tagCount
   FROM items AS t1
      INNER JOIN tagged AS t2 ON t1.item_id = t2.item_id
   WHERE tag IN ('how', 'jkas', 'bodor', 'zimp', 'ctuo', 'sjex', 'kek')
   GROUP BY item_id
) t
ORDER BY tagCount DESC, created DESC 
LIMIT 0 , 100