1052:字段列表中的列"id"不明确 [英] 1052: Column 'id' in field list is ambiguous

查看:317
本文介绍了1052:字段列表中的列"id"不明确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2张桌子. tbl_namestbl_section都具有id字段.如何选择id字段,因为我总是会收到此错误:

1052: Column 'id' in field list is ambiguous

这是我的查询:

SELECT id, name, section
  FROM tbl_names, tbl_section 
 WHERE tbl_names.id = tbl_section.id

我可以选择所有字段并避免错误.但这将浪费性能.我该怎么办?

解决方案

SQL通过给引用添加全表名作为前缀来支持对列进行限定:

SELECT tbl_names.id, tbl_section.id, name, section
  FROM tbl_names
  JOIN tbl_section ON tbl_section.id = tbl_names.id 

...或表别名:

SELECT n.id, s.id, n.name, s.section
  FROM tbl_names n
  JOIN tbl_section s ON s.id = n.id 

推荐使用表别名-为什么键入比您要多的文字?

为什么这些查询看起来不同?

第二,我的答案使用ANSI-92 JOIN语法(您使用的是ANSI-89).尽管它们执行相同的操作,但ANSI-89语法不支持外部连接(右,左,全).应该认为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"不明确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆