A 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
有一個SQL的設置結構,必須堅持或系統不知道你在做什麼@Till答案是最好的,看到的語法和特定的結構;) – glh 2013-04-24 10:59:53