我有两张桌子"用户"并且"用户设置"
我希望选择用户设置所在的用户 什么查询会更快?
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
OR
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
你能帮帮我吗?
谢谢
答案 0 :(得分: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;
您在UserSetting
上有过滤条件,因此无论如何外部联接都会转到内部联接。您应该避免使用隐式join
语法,并将连接条件显式放在on
子句中。这是为了可读性和可维护性。两个版本都应具有相同的性能。