简体   繁体   English

sql 内左连接 + 性能

[英]sql inner and left join + performance

I have 3 tables:我有 3 张桌子:

room
room location
room_storys

If anyone creates a room, everytime comes a row automaticlly to room location.如果有人创建房间,每次都会自动排到房间位置。 room_storys table can be empty. room_storys 表可以是空的。

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.每种JOIN类型都有其优点和缺点,但是对于像您这样的查询,“成本”可以忽略不计。 One recommendation would be to have the tables reference each other rather than a specific id as part of the ON clause.一个建议是让表相互引用而不是作为ON子句的一部分的特定id Specificity can be crucial with OUTER JOIN s in some situations.在某些情况下,特异性对于OUTER JOIN至关重要。 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 .此更改解决了返回room所有内容的问题,该问题已通过LIMIT 1得到缓解。 It also ensures a record is returned even if there is nothing in room_stories for the room_id .即使room_id中没有room_stories的内容,它也可以确保返回记录。

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表示表是如何相关的,例如

 ON room.id = room_story.room_id

WHERE is used for filtering, such as WHERE用于过滤,如

 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.此外, JOIN (或INNER JOIN要求 2 个表中的每一个中的匹配行都存在LEFT JOIN表示表中的匹配行可选地丢失。

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这变得无关紧要(我认为): LIMIT 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM