在where子句中使用condition更好还是join子句?

时间:2017-08-02 16:37:05

标签: mysql sql

请假设此查询:

SELECT p.* FROM posts p
JOIN posts_tags pt ON pt.post_id = p.id
JOIN tags t ON pt.tag_id = t.id AND t.name = 'php'

SELECT p.* FROM posts p
JOIN posts_tags pt ON pt.post_id = p.id
JOIN tags t ON pt.tag_id = t.id
WHERE t.name = 'php'

如您所知,两者都有相同的结果。但是这个条件t.name = 'php'在第一个查询的JOIN子句中,并且在第二个查询的WHERE子句中。我想知道哪一个更好,为什么?

1 个答案:

答案 0 :(得分:0)

通常,在j子句中添加条件会使代码更清晰。将它们添加到AND子句时,它会让人觉得JOIN基于两个字段的组合。

在大型表的情况下,将条件添加到Where子句可能有助于优化器在加入之前过滤掉记录。我建议将其保留在Dim repHolder() As String Dim strHolder() As String Dim counter As Variant Dim j As Integer For Each rep In repNames() repHolder() = Split(rep, ",") Next rep For Each rangeCell In repComboRange k = 1 Do If rangeCell.Value = repCombos(k) Then 'At this point, if rangecell = repcombos(k) Range(rangeCell, rangeCell.End(xlToRight)).Copy strHolder() = Split(rangeCell.Value, "/") For Each counter In strHolder() Stop For j = 1 To 17 If repHolder(j) = counter Then 条款中。

修改 另请参阅此相关帖子:Join best practices