我有3个数据库表:sitepaperlinkTable

 idSite     SiteName
 --------------------
   1           AAA
   2           BBB
   3           CCC


idPaper     PaperName
------------------------
   1           Paper1
   2           Paper2
   3           Paper3
   4           Paper4


idLinkTable    idSite   idPaper
----------------------------------
     1           1         1
     2           1         3
     3           2         1


我想显示所有没有idPaper=1idPaper=3表示idSite=1的论文;
同样,对于idSite=2,需要所有没有idPaper=1的论文。这是必需的输出:

SiteName  PaperName
------------------------
   AAA         Paper2
   AAA         Paper4
   BBB         Paper2
   BBB         Paper3
   BBB         Paper4


我已经试过这段代码:

SELECT s.SiteName AS Site, p.PaperName AS Paper
 FROM site s
INNER JOIN linkTable l ON s.idSite = l.idSite
INNER JOIN paper p ON l.idPaper != p.idPaper;


这是我使用以下代码时的结果:

SiteName  PaperName
------------------------
   AAA         Paper2
   AAA         Paper3
   AAA         Paper4
   AAA         Paper1
   AAA         Paper2
   AAA         Paper4
   BBB         Paper2
   BBB         Paper3
   BBB         Paper4

最佳答案

您需要SitePaper表之间的所有可能组合,但linkTable中已经存在的组合除外。使用CROSS JOIN获取所有可能的组合,并使用NOT EXISTS消除linkTable中已经存在的结果。请尝试以下操作:

SELECT s.SiteName AS Site, p.PaperName AS Paper
FROM site s
CROSS JOIN paper p
WHERE NOT EXISTS ( SELECT idLinkTable FROM linkTable
                   WHERE linkTable.idSite = s.idSite
                     AND linkTable.idPaper = p.idPaper
                 )

关于mysql - PHP从3个表中选择,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52168197/

10-13 02:22