WHERE
子句必须位于表列表的末尾,在可选的ORDER BY
. 查看 SELECT 语句必须遵守的结构定义:
SELECT
[ DISTINCT | ALL ]
<select list>
FROM <table reference list>
[ <where clause> ] <-- THIS IS THE INTERESTING PART
[ <group by clause> ]
[ <having clause> ]
[ UNION [ALL] <query specification> ]
[ <order by clause> ]
所以你的查询应该是这样的:
SELECT *, COUNT(my_other_table.id) AS c_others
FROM my_accounts
LEFT JOIN my_other_table ON my_accounts.id = my_other_table.account_connection
WHERE my_other_table.active = 1
ORDER BY my_accounts.name
您还可以将条件添加到您的ON
子句中:
SELECT *, COUNT(my_other_table.id) AS c_others
FROM my_accounts
JOIN my_other_table ON
my_accounts.id = my_other_table.account_connection
AND my_other_table.active = 1
ORDER BY my_accounts.name
该AS
语句除了为选定字段指定别名外,什么都不做。当字段名太长时,这可能很有用,您想为函数调用定义一个名称(例如COUNT(column) AS counter
,就像您使用它一样)或在连接具有相似列名的表时避免名称冲突。您还可以使用AS
为表名指定别名以避免必须多次键入它。
编辑:
正如 HamletHakobyan 的评论中所述:COUNT
是一个聚合函数,可能需要您GROUP BY
在语句中选择的其他字段上使用子句。因此,您需要将其扩展*
为实际的字段名并这样做:
SELECT
my_accounts.name,
my_accounts.firstname,
COUNT(my_other_table.id) AS c_others
FROM my_accounts
JOIN my_other_table ON
my_accounts.id = my_other_table.account_connection
AND my_other_table.active = 1
GROUP BY my_accounts.name, my_accounts.firstname
ORDER BY my_accounts.name