I have 3 tables:
room
room location
room_storys
If anyone creates a room, everytime comes a row automaticlly to room location. room_storys table can be empty.
Now I want to inner join the tables.
If I make this I get no results:
SELECT
r.name,
r.date,
rl.city,
rl.street,
rl.number,
rl.name,
rs.source,
rs.date
FROM room r
INNER JOIN room_location rl
ON rl.room_id = 67
INNER JOIN room_storys rs
ON rs.room_id = 67
LIMIT 1;
If I make this:
INNER JOIN room_storys rs
ON rs.room_id = 67
to this:
LEFT JOIN room_storys rs
ON rs.room_id = 67
```
then it works. But I heard that left join has no good performance, how you would perform this query above? Or is that okey?
Every JOIN
type has its pros and cons but, for a query like yours, the “cost” is negligible. One recommendation would be to have the tables reference each other rather than a specific id
as part of the ON
clause. Specificity can be crucial with OUTER JOIN
s in some situations. Your query can be written like this:
SELECT r.`name`,
r.`date`,
rl.`city`,
rl.`street`,
rl.`number`,
rl.`name`,
rs.`source`,
rs.`date`
FROM `room` r INNER JOIN `room_location` rl ON r.`id` = rl.`room_id`
LEFT OUTER JOIN `room_storys` rs ON rl.`room_id` = rs.`room_id`
WHERE r.`id` = 67;
This change solves the problem of returning everything in room
, which was mitigated by the LIMIT 1
. It also ensures a record is returned even if there is nothing in room_stories
for the room_id
.
Hope this gives you something to think about with future queries
Think of it this way:
ON
says how the tables are related, such as
ON room.id = room_story.room_id
WHERE
is used for filtering, such as
WHERE room.id = 67
Also, JOIN
(or INNER JOIN
requires the matching rows in each of the 2 tables to both exist. LEFT JOIN
says that the matching row in the right table is optionally missing.
Putting those together, I think this is what you needed:
FROM room r
INNER JOIN room_location rl ON rl.room_id = r.id
INNER JOIN room_storys rs ON rs.room_id = r.id
WHERE r.id = 67
This becomes irrelevent (I think): LIMIT 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.