将两个查询合二为一?

时间:2021-06-15 21:33:54

标签: php mysql left-join inner-join

我有一个 MySQL 查询,它从 audioids 表中的某个用户中选择所有 subscribe

然后我有另一个查询,它采用 audioids 的这个列表,并将它们与名为 opids 的表中名为 audioposts 的字段进行匹配。然后从该 titles 表中选择 audioposts,并在 users 处加入来自 userid 表的用户。

有没有办法将这两个查询变成一个查询?

query1 = "SELECT audioid FROM subscribe WHERE userid = $userid";                            
                    
query2 = "SELECT ap.audioid, ap.title, us.name FROM audioposts ap                   
        INNER JOIN audioposts a2 ON a2.audioid = ap.opid
        INNER JOIN users us ON us.id = a2.userid 
        WHERE ap.opid = $newaudio";

这是我想用一个查询替换的当前两个查询代码。我还没有把它翻译成准备好的陈述,因为我更容易用老式的方式将它形象化。另外,无论如何我最终都会将其转换为 NodejS;

    $selectaudioid = "SELECT audioid FROM subscribe WHERE userid = $userid";
    $audioResult=$dblink->query($selectaudioid);
    
        if ($audioResult->num_rows>0)   {       
            while ($row = $audioResult->fetch_assoc())  {
                $newaudio = $row[audioid];  
                $getallaudio = "                
                SELECT ap.audioid, ap.title, us.name FROM audioposts ap                     
                INNER JOIN audioposts a2 ON a2.audioid = ap.opid
                INNER JOIN users us ON us.id = a2.userid 
                WHERE ap.opid = $newaudio AND ap.opid <> '0'";
                
                $getallresult = $dblink->query($getallaudio);           
                
                if ($getallresult->num_rows>0)  {                       
                while ($row = $getallresult->fetch_assoc())  {
                    $dbdata[]=$row;                         
        }}}}

1 个答案:

答案 0 :(得分:1)

只需使用 subscribe 添加另一个连接。

SELECT ap.audioid, ap.title, us.name 
FROM audioposts ap                   
INNER JOIN audioposts a2 ON a2.audioid = ap.opid
INNER JOIN subscribe s ON s.audioid = ap.opid
INNER JOIN users us ON us.id = a2.userid 
WHERE s.userid = $userid AND ap.opid <> '0'