POSTS
[ id - post - content ]
----------------------------
[ 1 - 1post1 - 1content1]
[ 2 - 1post2 - 2content2]
VOTES
[ id - pid]
------------
[ 1 - 1]
[ 2 - 1]
[ 3 - 1]
[ 4 - 2]
[ 5 - 2]
1post1 = 3 votes
2post2 = 2 votes
当我尝试此查询时
$query = "SELECT a.title, a.content, b.COUNT(id) FROM posts a, votes b WHERE id = :id ORDER BY b.COUNT(id)";
它不起作用并给我这个错误
FUNCTION b.COUNT does not exist. Check the 'Function Name Parsing and Resolution
有更好的方法吗?我想过使用UNION ALL
就像这样
$query = "SELECT title, content, COUNT(id) FROM posts WHERE id = :id
UNION ALL
SELECT COUNT(id) FROM votes WHERE pid = :id";
但是这里的问题我将无法使用ORDER BY COUNT(id)
作为第一部分,这是我想根据第二部分订购的。
答案 0 :(得分:1)
只需删除b。 from count(id)...你正在使用一个函数,而不是一个表别名。
答案 1 :(得分:0)
COUNT()
等聚合时,如果您有非聚合字段(例如您的示例中的ID或帖子),则需要分组依据所以也许......(ANSI 92)
SELECT P.ID, P.Post, count(V.ID) as No_Votes
FROM Posts P
INNER JOIN Votes V
on V.PID = P.ID
WHERE P.ID = :id
GROUP BY P.ID, P.Post
ORDER BY No_votes -- due to order of operation we can use the column alias in an order by.
或......(ANSI 87)
SELECT P.ID, P.Post, count(V.ID) as No_Votes
FROM Posts P, Votes V
WHERE V.PID = P.ID
AND P.ID = :id
GROUP BY P.ID, P.Post
ORDER BY No_votes
也许你想要所有帖子,即使是那些没有投票的人,所以也许你需要使用OUTER JOIN(右/左而不是内在,取决于你以后的内容:你的例子和期望的结果不是除了内心以外什么都没有,所以我从这里开始了)