在网上遇到这个查询,用条件解释内连接(激励>3k)。只是想知道我是否可以在下面的 SQL 中使用 where 子句而不是“AND”,如果可以,输出差异是什么两者皆有?
SELECT FIRST_NAME,
INCENTIVE_AMOUNT
FROM employee a
INNER JOIN incentives B ON A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID
AND INCENTIVE_AMOUNT > 3000;
最佳答案
他们有相同的目标。
但是,通常认为最好的做法是仅使用 join
子句来指定连接,并将过滤谓词保留在 where
子句中,因此:
select first_name, incentive_amount
from employee e
join incentives i
on i.employee_ref_id = e.employee_id
where i.incentive_amount > 3000
(请注意,inner
和 outer
关键字是可选的,在我看来是多余的困惑,所以我从不使用它们。)
对于外连接(左连接
,或者如果绝对必须,左外连接
),分离过滤器谓词并将它们放入的整个想法where
子句超出了窗口范围,因为(例如)如果没有 incentive
行,则 i.incentive_amount
将为 null,因此任何谓词都会排除该行。有人说这就是为什么 ANSI 连接语法很垃圾,连接谓词和过滤谓词之间的区别是人为的、毫无意义的,而另一些人则认为这是一种有用的语法的怪癖。
select first_name, incentive_amount
from employee e
left join incentives i
on i.employee_ref_id = e.employee_id
and i.incentive_amount > 3000
您仍然可以遵循同一查询中内部联接的约定,例如:
select first_name, incentive_amount
from employee e
join departments d
on d.department_id = e.department_id
left join incentives i
on i.employee_ref_id = e.employee_id
and i.incentive_amount > 3000
where d.name = 'Philology'
补充一下,我同意 Jonathan Lewis a
和 b
对于 employee
和 incentives
来说是糟糕的别名。 (顺便说一句,为什么不employees
或incentive
?)在我的版本中,我使用了肯定更具可读性的e
和i
.
关于mysql - 我可以在给定的 SQL 查询中使用 where 子句而不是 AND 吗?如果是,两者有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46361132/