問題描述
我有兩張桌子.tbl_names
和 tbl_section
都包含 id
字段.我如何選擇 id
字段,因為我總是收到此錯誤:
1052: 字段列表中的列 'id' 不明確
這是我的查詢:
SELECT id, name, section從 tbl_names, tbl_section哪里 tbl_names.id = tbl_section.id
我可以選擇所有字段并避免錯誤.但這會浪費性能.我該怎么辦?
SQL 支持通過在引用前加上全表名來限定列:
SELECT tbl_names.id, tbl_section.id, name, section從 tbl_names在 tbl_section.id = tbl_names.id 上加入 tbl_section
...或表別名:
SELECT n.id, s.id, n.name, s.sectionFROM tbl_names n加入 tbl_section s ON s.id = n.id
表別名是推薦的方法——為什么要輸入更多的內容?
為什么這些查詢看起來不同?
其次,我的回答使用 ANSI-92 JOIN 語法(你的是 ANSI-89).雖然它們執行相同的操作,但 ANSI-89 語法不支持外部連接(RIGHT、LEFT、FULL).ANSI-89 語法應該被視為已棄用,SO 上有很多人不會投票支持 ANSI-89 語法來加強這一點.如需更多信息,請參閱此問題.>
I have 2 tables. tbl_names
and tbl_section
which has both the id
field in them. How do I go about selecting the id
field, because I always get this error:
1052: Column 'id' in field list is ambiguous
Here's my query:
SELECT id, name, section
FROM tbl_names, tbl_section
WHERE tbl_names.id = tbl_section.id
I could just select all the fields and avoid the error. But that would be a waste in performance. What should I do?
SQL supports qualifying a column by prefixing the reference with either the full table name:
SELECT tbl_names.id, tbl_section.id, name, section
FROM tbl_names
JOIN tbl_section ON tbl_section.id = tbl_names.id
...or a table alias:
SELECT n.id, s.id, n.name, s.section
FROM tbl_names n
JOIN tbl_section s ON s.id = n.id
The table alias is the recommended approach -- why type more than you have to?
Why Do These Queries Look Different?
Secondly, my answers use ANSI-92 JOIN syntax (yours is ANSI-89). While they perform the same, ANSI-89 syntax does not support OUTER joins (RIGHT, LEFT, FULL). ANSI-89 syntax should be considered deprecated, there are many on SO who will not vote for ANSI-89 syntax to reinforce that. For more information, see this question.
這篇關于1052:字段列表中的列“id"不明確的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!