在SQL中将WHERE添加到AS语句

car*_*777 0 sql

是否可以向AS添加WHERE语句?当我像这样运行sql总是失败.我只需要某种示例,我在搜索时无法找到任何堆栈.

SELECT *, 
COUNT(my_other_table.id) as 'c_others' WHERE my_other_table.active = 1
LEFT JOIN my_other_table on my_accounts.id = my_other_table.account_connection
FROM my_accounts
ORDER BY my_accounts.name
Run Code Online (Sandbox Code Playgroud)

注意我是如何添加WHERE my_other_table.active = 1的,这就是我打破一切的地方

我不是100%确定AS语句是如何工作的,通常我不会对它们做任何复杂的事情.但是现在我需要,我无法理解

Til*_*lge 5

一个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> ]
Run Code Online (Sandbox Code Playgroud)

所以你的查询应该是这样的:

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
Run Code Online (Sandbox Code Playgroud)

您还可以将条件添加到您的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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)