MySQL Extract data from two tables using internal join syntax

My two tables:

Entry
event_id   competitor_id   place
101        101             1
101        102             2
101        201             3
101        301             4
102        201             2
103        201             3

second table lists prizes for participating in events

Prize
event_id   place          money
101        1              120
101        2              60
101        3              30
102        1              10
102        2              5
102        3              2
103        1              100
103        2              60
103        3              40

From this, I want to show all the information from the Entry table along with the amount of money they won for their reputable placement. If they are not placed in money, then 0 will be displayed.

Any help would be appreciated.

+3
source share
3 answers

try the following:

SELECT  a.Event_ID, 
        a.Competitor_ID,
        a.Place,
        COALESCE(b.money, 0) as `Money`
FROM    entry a left join prize b
            on  (a.event_id = b.event_ID) AND
                (a.place = b.Place)

hope this helps.

EVENT_ID    COMPETITOR_ID   PLACE   MONEY
101           101            1      120
101           102            2       60
101           201            3       30
101           301            4        0   -- << this is what you're looking for
102           201            2        5
103           201            3       40
+6
source
SELECT * FROM Entry NATURAL LEFT JOIN Prize;

If you absolutely do not want 0instead of NULL“money” when the winnings were not won (but how can you distinguish the winnings from 0 and without winnings?):

SELECT Entry.*, COALESCE(money, 0) AS money FROM Entry NATURAL LEFT JOIN Prize;

Look at them like sqlfiddle .

+2

:

select e.*, coalesce(p.money, 0) money from entry e
left join prize p
on e.event_id = p.event_id and e.place = p.place

.

+2

All Articles