简体   繁体   中英

Ambiguous Column Name When Selecting From Multiple Tables

I am using SQL Server 2012 and during the selection of UserName from different tables I get the following error:

Msg 209, Level 16, State 1, Line 6 Ambiguous column name 'UserName'

SELECT *
FROM   Signup,
       Pers_D,
       Edu_D,
       Dep_S
WHERE  UserName LIKE '%Hwl123%';

This cannot be accomplished in that way. Comma says - you are trying to join those tables. Not union.

You are getting error Ambiguous column name 'UserName' because several tables have column with that name and server does not understand where to apply this filter.

In simple statements solution could look like:

SELECT *
FROM   Signup as s
WHERE  s.UserName LIKE '%Hwl123%'

UNION ALL

SELECT *
FROM   Pers_D as p
WHERE  p.UserName LIKE '%Hwl123%'

UNION ALL

SELECT *
FROM   Edu_D as e
WHERE  e.UserName LIKE '%Hwl123%'

UNION ALL

SELECT *
FROM   Dep_S as d
WHERE  d.UserName LIKE '%Hwl123%'

This is literally what you are attempting to do.

But your approach is leading you somewhere there:

SELECT s.*, p.*, e.*, d.*
FROM   Signup s
INNER JOIN Pers_D p ON p.??? = s.???
INNER JOIN Edu_D e on e.??? = ???
INNER JOIN Dep_S d on d.??? = ???
WHERE  [???].UserName LIKE '%Hwl123%' ---<<< ambiguity: s.UserName? p.UserName? e.UserName? d.UserName?

UserName is in more than one table. Try using an alias

I also don't see a JOIN, you will get much more than you probably expected

SELECT *
FROM Signup A,Pers_D B,Edu_D C,Dep_S D
WHERE A.UserName LIKE '%Hwl123%';

That syntax is actually giving you a cross join, which is every row in every table TIMES every row in the other tables. Probably not what you want.

The SELECT * is giving you every column from the 4 tables. At least 2 of those tables have a username column.

An easy way to see the columns in the Signup table is

SELECT TOP 10 * from Signup

You can use this on each table to see which tables have UserName in them.

You can ALIAS the tables and then specify which table you want to compare the UserName to in the WHERE column. For example:

SELECT *
FROM   Signup AS S,
       Pers_D AS P,
       Edu_D AS E,
       Dep_S AS D
WHERE  P.UserName LIKE '%Hwl123%';

Unless the CROSS JOIN is what you were going for, you really should rewrite that query as a series of JOINs based on columns that the tables share.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM