从这四个获取单个MySql查询

时间:2015-02-16 06:52:54

标签: php mysql

想要在单个 mysql查询中结合 4个查询 ,我当前的查询是

$sql1 = "SELECT * FROM projectFiles pf  
        INNER JOIN projectFileFolders pff ON pf.folderID = pff.folderID 
        WHERE pff.projectID =  '".$row['projectID']."' AND folderType=3"

$sql2 = "SELECT * FROM projectFiles pf 
        INNER JOIN projectProducts pp ON pf.fileID = pp.fileID 
        WHERE pp.projectID =  '".$row['projectID']."'"

$sql3 = "SELECT * FROM projectFiles pf  
        INNER JOIN projectMaintenance pm ON pf.fileID = pm.fileID 
        WHERE pm.projectID =  '".$row['projectID']."' "

$sql4 = "SELECT * FROM projectFiles pf  
        INNER JOIN projectServices ps ON pf.fileID = ps.fileID 
        WHERE ps.projectID =  '".$row['projectID']."' " 

1 个答案:

答案 0 :(得分:1)

如果我正确理解您的要求,您有四个表,并且您希望包含那些其projectID与您提供的$row['projectID']字段中的表匹配的表中的任何记录。如果是这样,您可以简单地将所有查询组合在一起:

$sqlWhatever = 
    "SELECT * FROM projectFiles pf  
     INNER JOIN projectFileFolders pff ON pf.folderID = pff.folderID 
     INNER JOIN projectProducts pp ON pf.fileID = pp.fileID 
     INNER JOIN projectMaintenance pm ON pf.fileID = pm.fileID 
     INNER JOIN projectServices ps ON pf.fileID = ps.fileID 
     WHERE pff.projectID =  '".$row['projectID']."' AND folderType=3
        OR pp.projectID =  '".$row['projectID']."' 
        OR pm.projectID =  '".$row['projectID']."' 
        OR ps.projectID =  '".$row['projectID']."' " 

现在,您还没有说过四个表中的每个表是否具有相同的fileID。如果他们不这样做,那么将INNER联接更改为LEFT联接,或者只获得在四个表中每个表中都有共同文件ID的记录。