查询
$query = "SELECT a.title, a.content, SUM(b.rating) as rating FROM posts a, ratings b WHERE a.id = :id AND a.id = b.pid GROUP BY b.author ORDER BY rating";
取决于这些表
posts ratings
[ id - title - content - author ] [ pid - rating - author ]
-------------------------------------- ---------------------------
[ 1 - title1 - content1 - author1 ] [ 1 - 8 - author1 ]
[ 2 - title1 - content2 - author2 ] [ 1 - 5 - author1 ]
[ 3 - title1 - content4 - author3 ] [ 1 - 9 - author2 ]
[ 4 - title4 - content4 - author4 ] [ 1 - 6 - author4 ]
[ 5 - title5 - content5 - author5 ] [ 5 - 3 - author5 ]
现在我正在尝试按ORDER
所有评分SUM
WHERE
a.id = b.pid AND a.author = b.author
发帖WHERE a.id = p.id
但是它没有按照预期进行排序,如果根本没有评级,则整个查询值变为空,因为子句id
为空,我想将其设为SUM = 0,我该如何解决这个问题?
如果在1
编辑时echo
为author1, author2, author4
ORDER
但它只是随机显示select table1.*, table2.date_in, table2.description
from table1 left outer join table2 on table1.id_t1 = table2.id_table1_fk
,如果评级表为空,则根本不会调用任何值。
答案 0 :(得分:0)
从不在FROM
子句中使用逗号。 始终使用正确的JOIN
语法。
要弄清楚你想要什么有点困难。但是你似乎非常关注作者,尽管作者在你的查询中扮演的角色很小。这就是你所描述的:
SELECT p.author, SUM(r.rating) as sumrating
FROM posts p LEFT JOIN
ratings r
ON p.id = r.pid AND p.author = r.author
WHERE a.id = :id
GROUP BY p.author
ORDER BY sumrating;
它对我来说似乎没什么用。