我正在尝试将3个MySQL查询合并为一个。
这是我用来抓取我的新闻条目(带分页):
SELECT A.sid,
A.title,
A.time,
A.bodytext,
A.author,
A.url
FROM news A
INNER JOIN
(SELECT sid
FROM news
WHERE approved=1
ORDER BY sid DESC LIMIT $start, $limit) B USING (sid)
现在,我最近添加了评论功能,希望获得每个“sid”的评论总数
让我感到困惑的部分是我需要将“sid”(来自news.news)与“page_id”(来自comments.pages)相匹配,以获取它独特的“id”。
+----+---------+
| id | page_id |
+----+---------+
| 1 | 87 |
| 2 | 86 |
| 41 | 85 |
| 3 | 84 |
| 13 | 83 |
+----+---------+
现在有了这个唯一的“id”,我需要查询“comments.comments”并将其与“page_id”列匹配并计算(*)它有多少条评论 - WHERE is_approved = 1
SELECT page_id,is_approved,count(*) FROM comments WHERE page_id = $id and is_approved = 1;
+---------+-------------+----------+
| page_id | is_approved | count(*) |
+---------+-------------+----------+
| 1 | 1 | 2 |
+---------+-------------+----------+
这可能吗?
答案 0 :(得分:1)
编辑我的回复以符合更新后的问题:
SELECT A.sid, A.title, A.time, A.bodytext, A.author, A.url,
D.page_id, D.num_comments
FROM news.news A
INNER JOIN (SELECT sid
FROM news
WHERE approved=1
ORDER BY sid desc
LIMIT $start, $limit) B USING (sid)
LEFT JOIN comments.pages C ON A.sid = C.id
LEFT JOIN (SELECT page_id,is_approved,count(*) as num_comments
FROM comments.comments
WHERE is_approved = 1) D ON C.page_id = D.page_id