我如何INNER JOIN另外两列到表?

时间:2017-02-24 09:41:12

标签: sql sql-server

我有一个SQL语句:

SELECT * FROM newsTable INNER JOIN picTable on picTable.picID = newsTable.newsPicID

这会将所选图像从一个表格链接到另一个表格中的新闻报道。

这仅适用于一个图像,但如果我要为一个故事添加最多3个图像,那么我的新SQL语句会是什么样子?

我无法理解 SQL语句的语法。

非常感谢任何指导。

newsTable

newsID
newsTitle
newsBody
newsPicID
newsPicIDTwo
newsPicIDThree

picTable

picID
picFileName
picPath

6 个答案:

答案 0 :(得分:3)

您可以再加入两次以获取图片信息:

SELECT t1.*,
       COALESCE(t2.picFileName, 'NA') AS picFileName1,
       COALESCE(t3.picFileName, 'NA') AS picFileName2,
       COALESCE(t4.picFileName, 'NA') AS picFileName3
FROM newsTable t1
LEFT JOIN picTable t2
    ON t1.newsPicID      = t2.picID
LEFT JOIN picTable t3
    ON t1.newsPicIDTwo   = t3.picID
LEFT JOIN picTable t4
    ON t1.newsPicIDThree = t4.picID

您可以根据需要在picTable添加更多列,如果新闻项目没有任何图片信息,可以再次使用COALESCE()提供默认值。

答案 1 :(得分:2)

也许是这样的:

SELECT newsTable.*, pic.*, picTwo.*, picThree.*
FROM newsTable
INNER JOIN picTable AS pic on picTable.picID = newsTable.newsPicID 
INNER JOIN picTable AS picTwo on picTable.picID = newsTable.newsPicIDTwo
INNER JOIN picTable AS picThree on picTable.picID = newsTable.newsPicIDThree

如果newsPicIDTwo或newsPicIDThree为NULL,则应使用LEFT OUTER JOIN

答案 2 :(得分:1)

left join picTable三次:

select *
from newsTable t
left join picTable p1 on p1.picID = t.newsPicID
left join picTable p2 on p2.picID = t.newsPicIDTwo
left join picTable p3 on p3.picID = t.newsPicIDThree

答案 3 :(得分:1)

Use LEFT OUTER JOIN to get three pictures :

SELECT * FROM newsTable 
LEFT OUTER JOIN picTable PIC1 on PIC1.picID = newsTable.newsPicID
LEFT OUTER JOIN picTable PIC2 on PIC2.picID = newsTable.newsPicIDTwo
LEFT OUTER JOIN picTable PIC3 on PIC3.picID = newsTable.newsPicIDThree

答案 4 :(得分:1)

在描述您的问题时,您有从新闻到图像的1对多关系。这意味着每个新闻ID可以有多个图片。  表示您不需要newsPicIDTwo上的newsPicIDThreenewsTable字段,并且您需要在表newsid上使用字段picTable。简单地说,

SELECT * FROM newsTable INNER JOIN picTable on picTable.newsID = newsTable.newsID

如果picTable上的记录具有相同的newsIDpicID

,则会为您带来正确的结果

换句话说,当外键位于“许多”上时,正确解决了经典的1-Many关系。表。

在你的情况下,'很多' table为picTable,因为它有一个外键newsid

答案 5 :(得分:0)

再次加入appropraite专栏。我已经使用了Left连接,以防其中一个pic列为空

SELECT NT.*, p1.picFileName as P1File, p2.picFileName as P2File, p3.picFileName as P3File
FROM newsTable NT
LEFT JOIN picTable P1 
  on P1.picID = NT.newsPicID
LEFT JOIN picTable P2 
  on P2.picID = NT.newsPicIDtwo
LEFT JOIN picTable P3
  on P3.picID = NT.newsPicIDthree