简体   繁体   English

如何连接两个表并按第三个表排序?

[英]How to join two tables and order by a third table?

So I have three tables, however my SQL JOIN statement continuously returns the same result for some reason instead of returning all rows and ordering them by the third. 所以我有三个表,但是我的SQL JOIN语句由于某种原因连续返回相同的结果,而不是返回所有行并按第三个顺序对其进行排序。

This statement correctly works and returns the gName and uName as expected: 此语句正确运行并按预期返回gName和uName:

SELECT rpg.name AS gName, u.username AS uName FROM roleplay_gangs rpg LEFT JOIN users u on u.id = rpg.owner_id

However when I try to select and order it by a field within the third table, the result isn't as expected for some reason. 但是,当我尝试通过第三个表中的字段选择并排序时,由于某种原因,结果与预期不符。 I've looked around for a while and attempted multiple times but none seem to work for me, never had to join more than 2 tables and order at the same time. 我环顾了一段时间,尝试了多次,但似乎没有一个对我有用,从来不必同时加入两个以上的表和订单。

So... I attempted to try it with the third table: 所以...我尝试用第三张桌子试一下:

SELECT rpg.name AS gName, u.username AS uName, COUNT(rpgt.gang_id) AS gCount FROM roleplay_gangs rpg LEFT JOIN users u on u.id = rpg.owner_id LEFT JOIN roleplay_gangs_turfs rpgt on rpg.id = rpgt.gang_id ORDER BY gCount

result: 结果:

gName | uName | gCount
-----------------------
test  | hello | 2

expected: 预期:

gName | uName | gCount
-----------------------
test  | hello | 2
zmaj  | hello | 0
thir  | ajtea | 0

Any help is appreciated, able to post more details on request if required. 感谢您的帮助,如果需要,可以根据要求发布更多详细信息。

The fields you are selecting that you want to be unique in the results should be included in the group by clause when using aggregation such as count : 使用诸如count聚合时,您要在结果中唯一的字段应包含在group by子句中:

SELECT
    rpg.name AS gName, 
    u.username AS uName,
    COUNT(rpgt.gang_id) AS gCount
FROM 
    roleplay_gangs rpg
LEFT JOIN
    users u on u.id = rpg.owner_id
LEFT JOIN
    roleplay_gangs_turfs rpgt on rpg.id = rpgt.gang_id
GROUP BY
    rpg.name, 
    u.username 
ORDER BY gCount

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM