我正在尝试计算freelanceFeedback的顺序和计数顺序如下:
$sql = "SELECT authentication.*, (SELECT COUNT(*) FROM freelanceFeedback) as taskscount FROM authentication
LEFT JOIN freelanceFeedback
ON authentication.userId=freelanceFeedback.FK_freelanceWinnerUserId
WHERE `FK_freelanceProvider`=$what
ORDER BY taskscount DESC";
但是如果用户有多个反馈并且没有通过taskscount进行排序,那么我有多个输出。
我无法弄清楚'推文'是错误的......
**更新** 我想我自己也有:
$sql = "SELECT DISTINCT authentication.*,
(SELECT COUNT(*) FROM freelanceFeedback
WHERE FK_freelanceWinnerUserId=userId
) as taskscount
FROM authentication
WHERE `FK_freelanceProvider`=$what
ORDER BY taskscount DESC";
这只输出1个用户并按反馈量进行订购。
答案 0 :(得分:1)
使用COUNT()时,还需要使用GROUP BY:
SELECT authentication.userId,
COUNT(freelanceFeedback.id) AS taskscount
FROM authentication
LEFT JOIN freelanceFeedback
ON authentication.userId = freelanceFeedback.FK_freelanceWinnerUserId
WHERE `FK_freelanceProvider`= $what
GROUP BY authentication.userId
ORDER BY taskscount DESC
但是,这只有在你没有做SELECT *时才会起作用(无论如何这都是不好的做法)。不在COUNT位中的所有内容都需要进入GROUP BY。如果这包括文本字段,您将无法执行此操作,因此您需要对子查询执行JOIN操作。如果不这样做,MySQL不会抱怨,但它会严重减慢速度,而其他数据库会抛出错误,所以最好这样做:
SELECT authentication.userId,
authentication.textfield,
authentication.othertextfield,
subquery.taskscount
FROM authentication
LEFT JOIN (SELECT freelanceFeedback.FK_freelanceWinnerUserId,
COUNT(freelanceFeedback.FK_freelanceWinnerUserId) AS taskscount
FROM freelanceFeedback
GROUP BY FK_freelanceWinnerUserId) AS subquery
ON authentication.userId = subquery.FK_freelanceWinnerUserId
WHERE authentication.FK_freelanceProvider = $what
ORDER BY subquery.taskscount DESC
目前还不清楚FK_freelanceProvider是哪一个表,所以我假设它是身份验证。