更改查询以从辅助表添加结果

时间:2012-06-02 07:05:42

标签: php mysql

以下查询效果很好。现在我想添加另一个名为地址的表格,其中包含相同的submissionidzip变量。我想从地址中提取所有submissionid变量zip = '$zip',然后使用这些结果从提交中查找相应的title表格在下面的查询中。

$sqlStr = "SELECT title, points, submissionid
             FROM submission 
            WHERE zip = '$zip'
         ORDER BY points DESC, title ASC              
     LIMIT $offset, $rowsperpage";

1 个答案:

答案 0 :(得分:4)

您可以使用子查询

来实现此目的
$sqlStr = "SELECT title, points, submissionid
         FROM submission 
        WHERE submissionid IN(
              SELECT submissionid 
              FROM addreses
              WHERE zip = '$zip')
     ORDER BY points DESC, title ASC              
 LIMIT $offset, $rowsperpage";

参考:IN Subquery

或使用JOIN

$sqlStr = "SELECT s.title, s.points, s.submissionid
         FROM submission s 
         INNER JOIN addresses ad
         on ad.submissionid = s.submissionid
         WHERE ad.zip = '$zip'
     ORDER BY s.points DESC, s.title ASC              
 LIMIT $offset, $rowsperpage";

参考:JOIN

正如评论中提到的@AdrianCornish,INNER连接比子查询更快。所以你最好选择加入第二个选项。

SO Subqueries vs joins

上的相关主题