简体   繁体   English

MySQL使用内部联接语法从两个表中检索数据

[英]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. 如果他们不能放入钱中,那么将显示0。

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?): 如果在没有赢得任何奖金的情况下,如果您绝对希望“金钱”为0而不是NULL (但是如何区分0的奖金和没有的奖金?):

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

See them both on sqlfiddle . 在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 . 你可以在这里玩小提琴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM