Optimizing JOIN with WHERE
Lets say I have 2 tables. The first table, table_1, contains each posted content including
table_1
title,
author name,
email,
city_name, etc.
The second table provides a lookup for table_1. It has 2 columns,
table_2
city_id and
city_name.
For instance, city_id =1 corresponds to New York, city_id =2 corresponds to Chicago... and so on. Under the 'city' column in table1, the city_id is listed which can easily be joined with table 2, producing a readable city name.
Would the following statement be as efficient as using a WHERE with city_id? Reason being is开发者_开发知识库 that I would be filtering results based on a city which is a string and I don't want (or need?) to correlate each input to its matching ID number in table2.
SELECT table1.city, table2.city_name
FROM table1
WHERE table2.city_name=(input city name)
JOIN table2.city_name ON table2.city_id = table1.city
Because the join is an inner join the following should lead to equivalent execution plans. (That is, they should exhibit the same performance characteristics -- write the SQL clearly and let the SQL engine do the dirty optimization work.)
As presented in the other answers:
SELECT table1.*, table2.city_name
FROM table1
JOIN table2 ON table1.city_id = table2.city_id
WHERE table2.city_name = (city_input);
And, as what I believe is the "optimized form" presented in the question:
SELECT table1.*, t2.city_name
FROM table1
JOIN (SELECT * FROM table2
WHERE table2.city_name = (city_input)) AS t2
ON table1.city_id = t2.city_id
This is because of the Relation Algebra Model that SQL follows; at least under RA the equality ("selection") here can be moved across the join (a "natural join" in RA) while keeping the same semantics. Of course, "to make for certain", run a query analysis. The most basic form is using EXPLAIN
.
Happy coding.
I'm not exactly following what the question is, but I'll say that the proper way to handle a query in which you need to filter on a specific city name, rather than ID, would be like this:
SELECT table1.*, table2.city_name
FROM table1
JOIN table2 ON table1.city_id = table2.city_id
WHERE table2.city_name = (city_input);
精彩评论