如何通过select语句中的ID从另一个表中进行选择?

时间:2019-03-02 01:06:22

标签: sql

我有三个表,一个表用于post_replies,一个表用于reply_likes(记录为“ likes”),另一个表用于Reply_dislikes。

reply_likes的reply_id列对应于post_replies表中的id列。

从本质上讲,我试图执行一种类似于foreach的操作,其中对于每个帖子回复,从reply_likes表中检索喜欢的次数。

对于reply_dislikes表也是如此。

post_replies表:

 +-------+-----------+------------+---------------+-------------+---------------+
 |  id   |  post_id  |  owner_id  | reply_content | created_at  |  is_shown     |
 +-------+-----------+------------+---------------+-------------+---------------+
 | int   |   int     |    int     |   text        |  timestamp  |    bool       |
 +-------+-----------+------------+---------------+-------------+---------------+

reply_likes表:

+-------+---------+-----------+
|  id   | user_id | reply_id  |
+-------+---------+-----------+
|  int  |  int    |  int      |
+-------+---------+-----------+

我尝试了以下操作,但不起作用:

 SELECT fc.id AS replyId, user.username AS owner, fc.reply_content AS content, 
 fc.created_at AS createdAt, COUNT(rl.id) AS likes
 FROM forum_replies fc 
 JOIN users user
 ON fc.owner_id = user.id 
 JOIN reply_likes rl 
 ON fc.id = rl.reply_id
 WHERE fc.post_id = :postId AND fc.is_shown = 1
 ORDER BY fc.created_at DESC

这种方法的问题在于,尚未检索fc.id以便从其他表中进行选择

2 个答案:

答案 0 :(得分:0)

在尝试选择诸如count之类的功能时,应该对表进行分组。答案将如下所示:

SELECT fc.id AS replyId, user.username AS owner, fc.reply_content AS content, 
 fc.created_at AS createdAt, COUNT(rl.id) AS likes
 FROM forum_replies fc 
 JOIN users user
 ON fc.owner_id = user.id 
 JOIN reply_likes rl 
 ON fc.id = rl.reply_id
 WHERE fc.post_id = (I do not know what does it mean):postId AND fc.is_shown = 1
 GROUP BY fc.id, user.username, fc.reply_content, fc.created_at
 ORDER BY fc.created_at DESC

只有我不明白这是什么意思“ fc.post_id =:postId”。另外,在添加“分组依据”后,您的代码脚本将可以正常工作。

答案 1 :(得分:0)

您需要使用group by来使count()正常工作:

SELECT fc.id AS replyId, user.username AS owner, fc.reply_content AS content, 
 fc.created_at AS createdAt, COUNT(rl.id) AS likes
 FROM forum_replies fc 
 JOIN users user
 ON fc.owner_id = user.id 
 JOIN reply_likes rl 
 ON fc.id = rl.reply_id
 WHERE fc.post_id = :postId AND fc.is_shown = 1
 Group by fc.id, u.username, fc.reply_content, fc.created_at
 ORDER BY fc.created_at DESC