2015-03-31 72 views
0

一个新手的问​​题,可能是一个INNER JOIN与“AS”的声明,但我不能算出它的有点...的MySQL如何选择我需要什么,最有可能的内部联接

这是为基于MYSQL的竞争应用程序。我想选择两个img_id1和img_id2的“img_title”。我无法弄清楚如何做到这一点,仍然可以看到其标题被分配给相关_id1或_id2。

我的表:

  • 比赛
    • comp_id
    • img_id1
    • img_id2
  • on_deck
    • img_id
    • img_title

期望的结果:
comp_id | img_id1 | img_title1 | img_id2 | img_title2

回答

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

你需要为每个图像的加盟:

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_id1img_id2可以NULL

+0

我已经做了左连接到苏斯出遗漏/断开的链接,但除此之外,你键入比我更快。:) – 2015-03-31 15:55:46

+0

我觉得他需要选择只有一个竞争,使这个查询是这里的例子。 :) – 2015-03-31 15:59:15

0

该查询应该给你你想要的结果的比赛行。这还假定comp.img_id1comp.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领域,你需要做一些左联接。