简体   繁体   English

mysql在table1上退出条件连接

[英]mysql left join with condition on table1

I'd like to do a left join using only certain rows of the first table in mysql. 我想只使用mysql中第一个表的某些行进行左联接。 Currently I do something like: 目前,我正在执行以下操作:

SELECT students.* FROM students             
LEFT JOIN courses                           
ON students.id = courses.id                 
WHERE students.id = 6

But will mysql first select rows from table1 (students) satisfying students.id = 6, before doing the left join? 但是,在进行左联接之前 ,mysql是否会首先从table1(学生)中选择满足学生的行。 If not, is there a way to force mysql do to so? 如果没有,有没有办法强制mysql这样做呢? Thanks. 谢谢。

Yes there is, try this: 是的,请尝试以下操作:

SELECT students.* FROM students             
LEFT JOIN courses                           
ON students.id = courses.id                 
HAVING students.id = 6
LIMIT 1

It seems to me that you are trying to optimize for the DB. 在我看来,您正在尝试针对数据库进行优化。 If the query is not slow, and your testing data set is a reasonable proximation of the production DB, then it is not best practice to do so, for many reasons. 如果查询不是很慢,并且您的测试数据集是生产数据库的合理替代,那么出于多种原因,这样做并不是最佳实践。

With that said, (maybe I am not right, so ignore me) 话虽如此,(也许我不对,所以请忽略我)

I think your trying to say, "How can i speed things up, by limiting the number of rows that the DB looks at during the query" 我认为您试图说:“如何通过限制数据库在查询过程中查看的行数来加快处理速度”

The best way to do this, is ensure you have proper indexes on the tables, on the fields that your going to query. 最好的方法是确保要查询的表上的表上具有正确的索引。 Indexes are extremely fast. 索引非常快。 If you do not already index the .id fields of both tables, add those indexes to the DB, and that may solve your issue. 如果尚未为两个表的.id字段建立索引,请将这些索引添加到数据库中,这可能会解决您的问题。

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

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