如何根据丰度对行进行排序?
How can I order the rows based on the abundance?
这是我的查询:
SELECT posts.id, posts.title, posts.body, posts.keywords
FROM posts
INNER JOIN pivot ON pivot.post_id = posts.id
INNER JOIN tags ON tags.id = pivot.tag_id
WHERE tags.name IN ('html', 'php')
GROUP BY posts.id
它选择所有标记有 php
或 html
或两者的帖子。现在我需要在查询中添加 ORDER BY
子句并根据丰度对结果进行排序。我的意思是我需要将同时具有 php
和 html
标签的帖子放在结果的顶部。
我该怎么做?
学习使用 table 别名。它使查询更易于编写和阅读。但是,您只需要一个合适的 ORDER BY
:
SELECT p.id, p.title, p.body, p.keywords
FROM posts p INNER JOIN
pivot pi
ON pi.post_id = p.id INNER JOIN
tags t
ON t.id = pi.tag_id
WHERE t.name IN ('html', 'php')
GROUP BY p.id
ORDER BY COUNT(DISTINCT t.name) DESC;
这是我的查询:
SELECT posts.id, posts.title, posts.body, posts.keywords
FROM posts
INNER JOIN pivot ON pivot.post_id = posts.id
INNER JOIN tags ON tags.id = pivot.tag_id
WHERE tags.name IN ('html', 'php')
GROUP BY posts.id
它选择所有标记有 php
或 html
或两者的帖子。现在我需要在查询中添加 ORDER BY
子句并根据丰度对结果进行排序。我的意思是我需要将同时具有 php
和 html
标签的帖子放在结果的顶部。
我该怎么做?
学习使用 table 别名。它使查询更易于编写和阅读。但是,您只需要一个合适的 ORDER BY
:
SELECT p.id, p.title, p.body, p.keywords
FROM posts p INNER JOIN
pivot pi
ON pi.post_id = p.id INNER JOIN
tags t
ON t.id = pi.tag_id
WHERE t.name IN ('html', 'php')
GROUP BY p.id
ORDER BY COUNT(DISTINCT t.name) DESC;