开发者

Which gives a faster query? Which is cleaner? JOIN ON or WHERE

When should I be using JOIN ON or WHERE in a scenario like the one below?

DECLARE
  @PhoneNumber int = 5551234

-- JOIN ON
SELECT *
FROM Persons
JOIN Employees ON Persons.DateOfBirth = Employees.DateOfBirth AND
Persons.PhoneNumber = Employees.PhoneNumber
WHERE Persons.PhoneNumber = @PhoneNumber

-- WHERE
SELECT *
FROM Persons
JOIN Employees ON Persons.DateOfBirth = Employees.DateofBirth
WHERE Persons.PhoneNumber = @PhoneNumber AND Employees.PhoneNumber = @PhoneNumber

I'm aware that the first query will have one PhoneNumber column, while the second will have two. Will开发者_如何学Go this significantly affect the speed of the query?


Syntax errors aside, you're comparing ANSI-89 JOIN syntax (JOIN criteria in the WHERE clause) to ANSI-92 JOIN syntax (uses the JOIN keyword).

They perform identical to one another, but ANSI-89 lacks OUTER JOIN support so many databases have custom means of indicating OUTER joins:

database     ANSI-89 OUTER JOIN syntax
------------------------------------
Oracle       t1.column = t2.column(+)
SQL Server   t1.column =* t2.column

For sake of portability and readability--use ANSI-92 syntax.


For an inner join it makes no difference to the results whether predicates are put in the join condition or where clause.

I'd put stuff related to joining the tables in the join clause and stuff related to filtering in the where clause.

SELECT *
FROM Persons
JOIN Employee ON Persons.PhoneNumber = Employee.PhoneNumber
WHERE Persons.PhoneNumber = @PhoneNumber


JOIN is the right choice for... joining tables logically connected with foreign keys. The reason is that you can set up different kind of joins (left, right, inner, outer).

WHERE is more a logical filtering of rows.

In your simple example, it makes no real difference between the two.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜