我在下面遇到了一个问题
SELECT ColumnName1,*
FROM TableName
WHERE ColumnName = 'XXXXXX'
ORDER BY ColumnName1
从上面的查询中,它以歧义的列名Column Name1引发错误。
即使我没有使用过数字表,它也会引发这样的错误。谁能说出这背后的原因吗?
答案 0 :(得分:5)
因为SELECT
有两列称为ColumnName1
-一列明确放置在其中,而另一列则来自*
。这里有一些选择:
SELECT t.ColumnName1, t.*
FROM TableName t
WHERE t.ColumnName = 'XXXXXX'
ORDER BY t.ColumnName1
或:
SELECT t.ColumnName1, t.*
FROM TableName t
WHERE t.ColumnName = 'XXXXXX'
ORDER BY 1
或:
SELECT t.ColumnName1 as second_columnname1, t.*
FROM TableName t
WHERE t.ColumnName = 'XXXXXX'
ORDER BY second_columnname1
答案 1 :(得分:0)
要解决错误,我们提供3个选项:
-- 1. give alias to the column
SELECT A AS A_STANDS_ALONE, *
FROM YourTable
ORDER BY A
-- 2. order by 1
SELECT A, *
FROM YourTable
ORDER BY 1
-- 3. give alias to the table and used it in column call and order by
SELECT t.A, *
FROM YourTable t
ORDER BY t.A