简体   繁体   中英

Ordering of grouped rows in mysql

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

How to order items by how many matches they have with IN TAG? I went really deep in manual and I couldn't find the answer and I got lost in stuff I don't understand.

You can use COUNT and put the results in a subquery:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM