LEFT OUTER JOIN和WHERE在连接表上

时间:2014-04-19 20:52:15

标签: mysql

详细说明,我正在从项目和位置表中选择字段。连接是来自items表的location_id和来自locations表的id字段。在连接之后,我正在从位置表中对city_text字段执行WHERE语句。

这是合法的行为,因为我在第二张桌子的字段上做了什么?

SELECT uc_items.* ,
       uc_users_store.id AS store_id,
       uc_users_store.store_name,
       uc_users_store.address,
       uc_users_store.work_hours,
       uc_locations.city_text AS city,
       uc_locations.zipcode_text AS zipcode,
       uc_locations.state_text AS STATE,
       uc_locations.country_text AS country
FROM uc_items
LEFT OUTER JOIN uc_users_store ON uc_items.store_id=uc_users_store.id
LEFT OUTER JOIN uc_locations ON uc_users_store.store_location_id=uc_locations.id
WHERE uc_locations.city_text LIKE "%'.$city.'%"
  AND uc_items.iname LIKE "%'.$description.'%"
  AND uc_items.expiration_stamp > '.time().'
ORDER BY uc_items.posting_stamp DESC,
         uc_items.discount DESC

2 个答案:

答案 0 :(得分:0)

这是合法的,但如果测试值为NULL,可能会导致意外结果。但是,您可以通过包含IS NULL检查来了解这些情况。

例如

WHERE (col = 'value' OR col IS NULL)

答案 1 :(得分:0)

完全合法。但是,使用INNER JOIN而不是LEFT JOIN更合乎逻辑,因为您的WHERE语句与您要加入的表有关。一个伪示例:

SELECT t1.something, t2.somethin FROM first_table t1 INNER JOIN second_table t2 ON t1.some_id = t2.some_id_from_t1 WHERE t2.some_column='something'