0
votes

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;
2

2 Answers

1
votes

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.

0
votes

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.