【问题标题】:using mysql what will be the fastest way to join tables使用 mysql 加入表的最快方法是什么
【发布时间】:2026-02-02 05:10:01
【问题描述】:

我有两个表“用户”和“用户设置”。

我想选择用户设置的地方 什么查询会更快?

SELECT u.*, us.someSettings FROM User u,UserSettings us 
WHERE u.id = us.user_id 
AND us.somesettings = somevalue 
AND u.someProperty = someOtherValue
AND u.someProperty1 = someOtherValue1
AND u.someProperty2 = someOtherValue2
AND u.someProperty3 = someOtherValue3
AND u.someProperty4 = someOtherValue4
AND us.someUSProperty  = someUSvalue

SELECT u.*, us.someSettings FROM User u
LEFT JOIN UserSettings us ON us.user_id = u.id
WHERE us.somesettings = somevalue 
AND u.someProperty = someOtherValue
AND u.someProperty1 = someOtherValue1
AND u.someProperty2 = someOtherValue2
AND u.someProperty3 = someOtherValue3
AND u.someProperty4 = someOtherValue4
AND us.someUSProperty  = someUSvalue

你能帮帮我吗 谢谢你

【问题讨论】:

标签: mysql sql performance select join


【解决方案1】:

正确的查询是内连接:

SELECT u.*, us.someSettings
FROM User u INNER JOIN
     UserSettings us
     ON us.user_id = u.id
WHERE us.somesettings = somevalue 
AND u.someProperty = someOtherValue
AND u.someProperty1 = someOtherValue1
AND u.someProperty2 = someOtherValue2
AND u.someProperty3 = someOtherValue3
AND u.someProperty4 = someOtherValue4
AND us.someUSProperty  = someUSvalue;

您在UserSettings 上有一个过滤条件,因此无论如何都会将外部联接转换为内部联接。您应该避免隐含的join 语法,并将连接条件显式放在on 子句中。这是为了可读性和可维护性。两个版本应该具有相同的性能。

【讨论】:

    最近更新 更多