简体   繁体   中英

join in sql query gives column ambigios error

table name - city

columns -city_id,city_name

table - state

column -state_id,state_name

table name - category

column name - category_id,category_name

table name - news

column name - cat_id,state_id,city_id,headline,story ,author etc..

I nedd to select all column from city,state,and category table for inserting id in news table....

for that I create sql query and join all above three table but this shows error ..plz help me...

Column 'state_id' in field list is ambiguous

Column 'city_id' in field list is ambiguous

Column 'category_id' in field list is ambiguous

I need to return all columns from city,state and category table

SELECT city_name,city_id,state_id,category_id,state_name,category_name,headline,author,story,source,photo,date from news left join
 city on news.city_id=city.city_id left join state on news.state_id=state.state_id left join category on news.cat_id=category.category_id;

You need to specify the tables where the columns come from. city_id is ambiguous in the select list. I think this is the right aliases:

SELECT c.city_name, c.city_id, s.state_id, ca.category_id, s.state_name, ca.category_name,
       n.headline, n.author, n.story, n.source, n.photo, n.date
from news n left join
     city c
     on n.city_id= c.city_id left join
     state s
     on n.state_id = s.state_id left join
     category ca
     on n.cat_id = ca.category_id;

Note that I introduced table aliases. These help make the query easier to write and to read.

Reason for the same is, you have state_id both in state and news table (same for city_id which is in City as well as news table) to name few and SQL engine is confused which one to use. Hence i would advice you to use table alias or table name as prefix in the select fields.

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