PHP select 来自 3 个表

PHP select from 3 tables

我有 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=1,idPaper=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 to get all possible combinations, and 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
                 )