我有一个posts
表和一个包含postmeta
和meta_key
列的meta_value
表。我在下面添加了一个简化的表结构(带有一些演示数据)。
CREATE TABLE `posts` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(200) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
INSERT INTO `posts` (`id`, `title`) VALUES
(1,'First post'),
(2,'Second post'),
(3,'Third post'),
(4,'Fourth post');
CREATE TABLE `postmeta` (
`meta_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`post_id` int(11) NOT NULL,
`meta_key` varchar(200) NOT NULL DEFAULT '',
`meta_value` text NOT NULL,
PRIMARY KEY (`meta_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
INSERT INTO `postmeta` (`meta_id`, `post_id`, `meta_key`, `meta_value`) VALUES
(1,1,'rating','80'),
(2,1,'total_votes','500'),
(3,2,'rating','80'),
(4,2,'total_votes','501'),
(5,3,'rating','95'),
(6,3,'total_votes','200');
帖子需要按评级排序。还需要包含没有任何评级的帖子,因此LEFT JOIN
。没问题:
SELECT *
FROM posts p
LEFT JOIN postmeta m ON p.id = m.post_id AND m.meta_key = 'rating'
ORDER BY m.meta_value DESC
但是,对于评分相同的帖子,我希望按照总计票数对其进行进一步排序,该计数存储在postmeta
表格的另一行中。在上面的示例中,第一个和第二个帖子的评级为80但由于第二个帖子有更多的投票,因此应该在第一个帖子之前订购。你会如何在一个查询中解决这个问题?
答案 0 :(得分:2)
SELECT * <-- you'll want to specify columns here
FROM posts p
LEFT JOIN postmeta m ON p.id = m.post_id AND m.meta_key = 'rating'
LEFT JOIN postmeta mv ON p.id = mv.post_id AND mv.meta_key = 'total_votes'
ORDER BY m.meta_value DESC, mv.meta_value DESC
<强>输出:强>
| ID | TITLE | META_ID | POST_ID | META_KEY | META_VALUE |
----------------------------------------------------------------
| 3 | Third post | 5 | 3 | rating | 95 |
| 2 | Second post | 3 | 2 | rating | 80 |
| 1 | First post | 1 | 1 | rating | 80 |
| 4 | Fourth post | (null) | (null) | (null) | (null) |
答案 1 :(得分:1)
SELECT *
FROM posts p
LEFT JOIN postmeta m ON p.id = m.post_id AND m.meta_key = 'rating'
LEFT JOIN postmeta m2 ON p.id = m2.post_id AND m2.meta_key = 'total_votes'
ORDER BY m.meta_value DESC, m2.meta_value Desc