有点新手问题,可能是INNER JOIN带有“AS”声明,但我无法弄明白......
这适用于基于MYSQL的竞赛应用。我想为img_id1和img_id2选择“img_title”。我无法弄清楚如何做,仍然看到哪个标题分配给关联的_id1或_id2。
我的桌子:
期望的结果:
comp_id | img_id1 | img_title1 | img_id2 | img_title2
答案 0 :(得分:2)
每张图片都需要加入:
SELECT comp.comp_id, img1.img_id, img1.img_title, img2.img_id, img2.img_title
FROM competitions comp
INNER JOIN on_deck img1 ON img1.img_id = comp.img_id1
INNER JOIN on_deck img2 ON img2.img_id = comp.img_id2
如果LEFT JOIN
或img_id1
可以是img_id2
,则 NULL
。
答案 1 :(得分:0)
select comp_id, img_id1, b.img_title as img_title1,
img_id2, b2.img_title as img_title2
from competitions a
left outer join on_deck b on b.img_id = a.img_id1
left outer join on_deck b2 on b2.img_id = a.img_id2
如果要在没有两个匹配的img_ids的比赛中排除行,请将外部联接设置为内部联接
答案 2 :(得分:0)
此查询应该为您提供所需的结果。这也假设comp.img_id1
和comp.img_id2
永远不会NULL
。
SELECT comp.comp_id
, comp.img_id1
, deck1.img_title AS img_title1
, comp.img_id2
, deck2.img_title AS img_title2
FROM competitions AS comp
JOIN on_deck deck1 ON comp.img_id1 = deck1.img_id
JOIN on_deck deck2 ON comp.img_id2 = deck2.img_id
如果您计划使用NULL
或空字符串comp.img_id1
和/或comp.img_id2
字段,则需要执行一些左连接。