[英]Ordering joined query by multiple rows of the joined table
我有一個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,但由於第二篇文章的投票較多,因此應在第一篇文章之前對其進行排序。 您將如何在單個查詢中實現?
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) |
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.