Mysql Select&订购1张桌子

时间:2014-10-27 07:03:29

标签: mysql sql

我是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')
;

我想选择和排序帖子:

  1. Hello => 2(喜欢)
  2. 这是title => 1(喜欢)

2 个答案:

答案 0 :(得分:3)

您可以执行自我加入,并根据喜欢的次数进行排序:

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

答案 1 :(得分:3)

SELECT p.`title`,COUNT(*),pl.`type` FROM posts p
JOIN posts pl ON pl.`post_id`=p.`id`
GROUP BY p.`id`;

让我知道这是否适合你。