[英]Ambiguous column name when doing a JOIN
我加入陈述书时遇到一些麻烦
这个还可以
select [db_id], COUNT(db_id) AS total
FROM [dbauditor_repo].[dbo].[dbauditor_repo_events]
GROUP BY [db_id]
ORDER BY total DESC
但是在进行连接时出现错误(模棱两可的列名“ db_id”。)
SELECT [db_name], [db_id], COUNT(db_id) AS total
FROM [dbauditor_repo].[dbo].[dbauditor_repo_events] JOIN [dbauditor_repo].[dbo].[dbauditor_repo_warehouse]
ON ([dbauditor_repo].[dbo].[dbauditor_repo_events].[db_id] = [dbauditor_repo].[dbo].[dbauditor_repo_warehouse].[db_id])
WHERE [db_type] = 'mysql'
GROUP BY [db_id]
ORDER BY total DESC
任何想法 ?
只是养成对所有列引用使用表别名的习惯。 这样可以防止此类错误和其他意外问题。 最佳实践是使用表的缩写。 这是一个例子:
SELECT rw.[db_name], re.[db_id], COUNT(re.db_id) AS total
FROM [dbauditor_repo].[dbo].[dbauditor_repo_events] re JOIN
[dbauditor_repo].[dbo].[dbauditor_repo_warehouse] rw
ON re.[db_id] = rw.[db_id])
WHERE rw.[db_type] = 'mysql'
GROUP BY rw.[db_name], re.[db_id]
ORDER BY total DESC;
当然,我必须猜测列来自哪个表。 您应该修复查询,以便它们来自正确的表。
另外,使用表别名时,查询更易于编写和阅读。
联接表时,您需要使用标准名称,并且该列存在于多个表中。
尝试:
SELECT [dbauditor_repo_events].[db_id]
您还需要在GROUP BY
子句中包括db_name
列,因为此列未聚合。
GROUP BY [dbauditor_repo_events].[db_id], [db_name]
在您的选择和分组依据中:
SELECT [db_name], [dbauditor_repo_events].[db_id], COUNT([dbauditor_repo_events].db_id) AS total
FROM [dbauditor_repo].[dbo].[dbauditor_repo_events] JOIN [dbauditor_repo].[dbo].[dbauditor_repo_warehouse]
ON ([dbauditor_repo].[dbo].[dbauditor_repo_events].[db_id] = [dbauditor_repo].[dbo].[dbauditor_repo_warehouse].[db_id])
WHERE [db_type] = 'mysql'
GROUP BY [dbauditor_repo_events].[db_id]
ORDER BY total DESC
您可能应该考虑在查询中为表加别名以提高可读性,例如:
SELECT [db_name], e.[db_id], COUNT(e.db_id) AS total
FROM [dbauditor_repo].[dbo].[dbauditor_repo_events] as e
JOIN [dbauditor_repo].[dbo].[dbauditor_repo_warehouse] as w
ON (e.[db_id] = w.[db_id])
WHERE [db_type] = 'mysql'
GROUP BY e.[db_id]
ORDER BY total DESC
问题:
这是因为:
[dbauditor_repo].[dbo].[dbauditor_repo_events]
和
[dbauditor_repo].[dbo].[dbauditor_repo_warehouse]
具有相同的列名称db_id。 查询不知道要使用哪个表的db_id。 因此,此错误。
解:
使用TableName.FieldName
或TableAliasName.FieldName
可以避免此错误。 将查询更改为:
SELECT [db_name],
TAB1.[db_id] ,
COUNT(TAB1.db_id) AS total
FROM
[dbauditor_repo].[dbo].[dbauditor_repo_events] AS TAB1
JOIN
[dbauditor_repo].[dbo].[dbauditor_repo_warehouse] AS TAB2
ON
(TAB1.[db_id] = TAB2.[db_id])
WHERE [db_type] = 'mysql'
GROUP BY [db_name],[TAB1.db_id]
ORDER BY total DESC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.