简体   繁体   中英

MySQL Retrieving data from two tables using inner join syntax

My two tables are

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 on offer for the 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 am looking to show all the information from the Entry table alongside the amount of money they won for their respected placing. If they failed to place in the money then a 0 will be displayed.

Any help would be appreciated.

try this:

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
SELECT * FROM Entry NATURAL LEFT JOIN Prize;

If you absolutely want 0 instead of NULL for the "money" when no prize was won (but how can you differentiate between a prize of 0 and no prize?):

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

See them both on sqlfiddle .

Try this:

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

You can play with the fiddle here .

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