我是 MySQL 新手。我有一个具有以下结构和数据的表:
CREATE TABLE posts
(`id` int, `title` varchar(255), `post_id` int, `type` varchar(255) )
;
INSERT INTO posts
(`id`, `title`, `post_id`, `type`)
VALUES
(1, 'Hello', NULL, 'post'),
(2, 'This is title', NULL, 'post'),
(3, NULL, 1, 'like'),
(4, NULL, 1, 'like'),
(5, NULL, 2, 'like')
;
我想像这样选择和排序帖子:
- 你好 => 2(喜欢)
- 这是标题 => 1(赞)
最佳答案
您可以执行自连接,并根据喜欢的数量进行排序:
SELECT id, cnt
FROM (SELECT id, title
FROM posts
WHERE title IS NOT NULL) titles
JOIN (SELECT post_id, COUNT(*) AS cnt
FROM posts
WHERE type = 'like'
GROUP BY post_id) likes ON titles.id = likes.post_id
ORDER BY cnt DESC
关于Mysql 在 1 个表上选择和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26582508/