将连接中的count(*)添加到查询中

时间:2013-12-20 22:08:43

标签: mysql sql

呃......我真的很难与这些mySQL联接......

这就是我追求的目标。我当前的查询看起来像这样。

SELECT profiles.photo, postings.postid, postings.text, postings.date, members.fname, members.lname, members.userid 
FROM profiles, postings, members
WHERE postings.wallid=postings.posterid 
AND postings.wallid=members.userid 
AND postings.wallid=profiles.userid 

我正在尝试添加来自另一个表的匹配记录的计数(*)。另一个表称为likespostings.postid = likes.post_id

我尝试过(并且没有返回结果)是这个...

SELECT profiles.photo, postings.postid, postings.text, postings.date, members.fname, members.lname, members.userid,
(SELECT COUNT(*) FROM likes WHERE postings.postid=likes.post_id)
FROM profiles, postings, members, likes
WHERE postings.wallid=postings.posterid 
AND postings.wallid=members.userid 
AND postings.wallid=profiles.userid 

我在这里做的是添加嵌套的SELECT,我认为可以解决这个问题。

基本上,我要问的是......在第一次查询的情况下,我怎样才能获得likespostings.postid = likes.post_id中记录数的计数?与往常一样,任何帮助/提示/建议总是受到赞赏。

2 个答案:

答案 0 :(得分:1)

试试:

 SELECT profiles.photo, postings.postid, postings.text, postings.date, members.fname,members.lname, members.userid,
 likes.like_count
 FROM profiles, members, postings
 LEFT JOIN (SELECT post_id, COUNT(*) like_count FROM likes GROUP BY post_id) as likes
      ON postings.postid=likes.post_id
 WHERE postings.wallid=postings.posterid 
 AND postings.wallid=members.userid 
 AND postings.wallid=profiles.userid 

答案 1 :(得分:1)

首先,为此使用新式sql语法要容易得多。从概念上讲,使用旧语法进行外连接会让人感到困惑和困难。其次,你错过了“个人资料”表,错误地似乎已经自我加入了帖子表。尝试更像这样编写查询:

SELECT 
    profiles.photo, 
    postings.postid, 
    postings.text, 
    postings.date, 
    members.fname, 
    members.lname, 
    members.userid,
    COUNT(DISTINCT like_id) as CountOfLikes
FROM profiles
INNER JOIN postings
    ON postings.wallid=profiles.userid 
INNER JOIN members
    ON members.userid=postings.wallid
LEFT JOIN likes
    ON likes.post_id = postings.post_id;