I used the following query
select a.*,b.* from firsttable a left join secondtable b on a.id=b.item_id ORDER BY a.id DESC LIMIT 0,10
To display items from two tables, where the id of the first table is the item_id of the second. My question is , when I try to display this in php , if I want to display a.id i can try with:
while($row=$go->fetch_assoc()){ echo $row['id']; }
or
while($row=$go->fetch_assoc()){ echo $row['a.id']; }
since both tables have id,on the first example displays only if there are matching rows from first and second table and displays the id of second table, I want the id of first
and on the second it says undefined index. Can you explain why is this please?
Edit: Adding tables for example
id info username id item.id username
Advertisement
Answer
Both tables have a column that has the same name, so, when using select *
, it is ambiguous to which column id
relates to.
The only way to remove the ambiguity is to explicitly list all the columns you want to select
, using aliases for homonyms:
select a.id, b.id b_id, -- alias for b.id b.item_id -- more columns here as needed from firsttable a left join secondtable b on a.id=b.item_id order by a.id desc limit 0,10
This is one of the many reasons why select *
is generally considered a bad practice in SQL.
Recommend reading: What is the reason not to use select *
?