INNER JOIN的Where子句 - 子集或原始表上的行为?

时间:2014-10-24 16:42:22

标签: mysql

鉴于此查询:

SELECT `promotions`.* 
FROM `promotions` 
    INNER JOIN `orders_promotions` ON `promotions`.`id` = `orders_promotions`.`promotion_id` 
WHERE `orders_promotions`.`order_id` = 3
AND `promotions`.`code` = 'blablabla'

我想知道最后一个WHEREWHERE `promotions`.`code` = 'blablabla')语句是针对WHOLE promotions表,还是针对INNER JOIN返回的集合?

1 个答案:

答案 0 :(得分:0)

执行SQL查询的操作顺序如下所示

FROM clause
JOIN clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause 

正如您在WHERE操作执行后看到JOIN所见;这表示在上面发布的查询中WHERE条件将对从JOIN操作获得的结果集起作用。

您可以更改查询并在JOIN ON子句中包含条件,以便在它到达WHERE子句之前进行过滤,如

SELECT `promotions`.* 
FROM `promotions` 
INNER JOIN `orders_promotions` 
ON `promotions`.`id` = `orders_promotions`.`promotion_id` 
AND `orders_promotions`.`order_id` = 3
WHERE `promotions`.`code` = 'blablabla'

您可能需要阅读This Article