How to join tables together - SQL

淺唱寂寞╮ 提交于 2019-12-02 08:20:44

问题


This is a SQL question

I have two tables I need to join together, using the inner join syntax. One named Entry, and the other named prize. I need to list the event_id, horse_id, place, money.

ENTRY (TABLE NAME)
COLUMNS IN TABLE ENTRY:
Event_id,
Horse_id
Place

PRIZE (TABLE NAME)
COLUMNS IN TABLE PRIZE:
Event_id,
Place,
Money

This is as far as I have got, I just can't get my head around it.

SELECT event_id, horse_id, place
FROM ENTRY INNER JOIN PRIZE
ON ENTRY.money = PRIZE.money

Thanks


回答1:


SELECT e.Event_id, e.Horse_id, e.place, p.money

FROM ENTRY e join Prize p

ON e.Event_id = p.Event_id

where e.place = p.place;

The e and p are used as aliases for the tables to avoid unreadable sql because of long table names.

using the e. or p. you will select the field for that table because it is possible that both tables have a field with the same name so there will be issues when executing the statement

I added the e.place = p.place because if you don't you would be getting the results for every place for each event matched with every prize

for example you would get Event 1 horse 1 place 1 prize 1 event 1 horse 1 place 1 prize 2 Event 1 horse 1 place 1 prize 3 event 1 horse 1 place 1 prize 4 etc... until you get every prize and this would be the same for every entry, assuming the event for the prize equals the event for the entry




回答2:


You should use alias to avoid ambiguity

select 
e.event_id,
e.horse_id,
e.place,
p.Money
from ENTRY e 
join PRIZE p on p.event_id = e.event_id


来源:https://stackoverflow.com/questions/29939975/how-to-join-tables-together-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!