我有一个表,每次创建一个帖子时都会创建一个记录,另一个表会在每次收到帖子时创建一个记录。
CREATE TABLE `posts` (
`post_id` bigint(20) NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
PRIMARY KEY (`post_id`)
)
CREATE TABLE `favorited_posts` (
`user_id` bigint(20) NOT NULL,
`post_id` bigint(20) NOT NULL,
KEY `user_id` (`user_id`),
KEY `post_id` (`post_id`),
FOREIGN KEY (`post_id`) REFERENCES `posts` (`post_id`)
)
以下查询返回一个结果集,该结果集显示帖子被收藏的次数
SELECT p.post_id, p.title,
COUNT(fp.post_id) as num_favorites
FROM posts p
LEFT JOIN favorited_posts fp
ON fp.post_id = p.post_id
WHERE p.post_id BETWEEN 0 AND 10000
GROUP BY 1;
+-------------------+----------------+
| post_id | title | num_favorites |
+-------------------+----------------+
| 1 | abc | 15 |
| 2 | hello | 0 |
| 3 | test | 7 |
+----------+--------+----------------+
如何更改查询以创建具有true / false,0/1值的ad-hoc列,该值表示用户是否已收藏特定帖子?它会产生这样的结果集(用户已经收到了第2和第3个帖子)
+-------------------+----------------+---------------+
| post_id | title | num_favorites | has_favorited |
+-------------------+----------------+---------------+
| 1 | abc | 15 | 0 |
| 2 | hello | 0 | 1 |
| 3 | test | 7 | 1 |
+----------+--------+----------------+---------------+
我可以检索特定用户在查询中收到的帖子,但不知道如何在捕获post_id,标题和收藏总数的单个查询中检索此信息。
SELECT * FROM favorited_posts
WHERE user_id = 10;
答案 0 :(得分:1)
只需使用左连接中的第二个查询:
SELECT p.post_id, p.title, IF(COUNT(fp.post_id)>0, 'True', 'False') as user_favorite
FROM posts p
LEFT JOIN (
SELECT post_id FROM favorited_posts
WHERE user_id = 10
) fp ON fp.post_id = p.post_id
WHERE p.post_id BETWEEN 0 AND 10000
GROUP BY 1;
另外,您错过了favorited_posts
表中user
的外键。
答案 1 :(得分:1)
您可以使用条件聚合:
SELECT p.post_id,
p.title,
COUNT(fp.post_id) as num_favorites,
sum(case when fp.user_id = 10 then 1 else 0 end) as has_favorited
FROM posts p
LEFT JOIN favorited_posts fp
ON fp.post_id = p.post_id
WHERE p.post_id BETWEEN 0 AND 10000
GROUP BY p.post_id, p.title
此查询与您现在的查询相同,不同之处在于它显示的列指示给定用户(在case语句中指定)是否已在给定行上的特定帖子中占用。