是否可以向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
注意我是如何添加WHERE my_other_table.active = 1的,这就是我打破一切的地方
我不是100%确定AS语句是如何工作的,通常我不会对它们做任何复杂的事情。但现在我需要,我无法弄清楚
答案 0 :(得分: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> ]
所以你的查询应该是这样的:
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
语句除了为所选字段指定别名之外别无其他。当fieldname太长,你想为函数调用定义一个名称(例如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
答案 1 :(得分:0)
您只需将WHERE
子句添加为:
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
GROUP BY <list all necessary fields>
ORDER BY my_accounts.name
或者,如果您想获得元素的选择性计数,请使用此
SELECT <list all necessary fields>,
COUNT(CASE WHEN my_other_table.active = 1 THEN my_other_table.id END) as 'c_others'
FROM my_accounts
LEFT JOIN my_other_table
ON my_accounts.id = my_other_table.account_connection
GROUP BY <list all necessary fields>
ORDER BY my_accounts.name
答案 2 :(得分:0)
AS
仅为对象(列,表等)引入了新的名称。因此,对它应用WHERE
没有意义(因为在这个例子中,列的名称)对于整个结果集是固定的。
猜测一下,您实际上想要修改COUNT
,以便您只计算active
为1的行:
SELECT *,
SUM(CASE WHEN my_other_table.active = 1 THEN 1 ELSE 0 END) as 'c_others'
LEFT JOIN my_other_table on my_accounts.id = my_other_table.account_connection
FROM my_accounts
ORDER BY my_accounts.name
答案 3 :(得分:0)
AS只是一个为列命名的关键字。这在复杂的列定义中很方便。该名称仅适用于查询结果,但不适用于查询 - 您无法在同一查询中引用它。那么你必须使用子查询。
WHERE(以及其他关键字)在Till Helge编写的查询中占有一席之地。