这是我要写的查询...
SELECT top 10 U.userid, U.fullname, U.username, T.tid, T.msg, T.tpic, T.ttime, COUNT(R.tid)
FROM USER_DETAILS AS U
INNER JOIN TWEET AS T ON U.userid = T.tuid
LEFT OUTER JOIN RETWEET AS R ON T.tuid = R.tid
WHERE (T.tuid IN (SELECT f.fuid FROM FOLLOW AS F WHERE F.userid = @usrid) OR T.tuid = @usrid)
ORDER BY T.ttime DESC;
我知道由于聚合而导致查询错误。我想要的只是被转发的推文的数量。那么更好的方法是什么呢?
表格是:
User_details(userid, fullname, username)
Follow(userid, fuid) where userid is following fuid
Tweet(tid, tuid)
Retweet(tid, ruid) where ruid is the user doing the retweet.
答案 0 :(得分:1)
如果你解释你如何知道它是错的以及你知道它是什么问题,它会很有用,所以我可以确信你的所有问题都得到了解决。但是,显而易见的是,您没有group by子句,这是聚合工作所需要的。
SELECT top 10 U.userid, U.fullname, U.username, T.tid, T.msg, T.tpic, T.ttime, COUNT(R.tid)
FROM USER_DETAILS AS U
INNER JOIN TWEET AS T ON U.userid = T.tuid
LEFT OUTER JOIN RETWEET AS R ON T.tuid = R.tid
WHERE (T.tuid IN (SELECT f.fuid FROM FOLLOW AS F WHERE F.userid = @usrid) OR T.tuid = @usrid)
GROUP BY U.userid, U.fullname, U.username, T.tid, T.msg, T.tpic, T.ttime
ORDER BY T.ttime DESC;