我无法让LEFT JOIN工作

时间:2016-01-12 22:04:57

标签: mysql join

SELECT *, 0 AS distance
FROM restaurants
WHERE   OPEN = '1'
    AND STATUS = '1'
    AND is_delivery = '1'
    AND NAME LIKE '%chuck%'
ORDER BY distance LIMIT 0, 10

这是我必须使用的基本SQL查询。我想在今天添加餐厅的营业时间。所有血腥的文档都说它应该像添加

一样简单
 LEFT JOIN hours ON (restaurants.id = hours.restaurant_id AND hours.day_of_week = 'Tuesday')

要合并它们,我试过了:

SELECT *, 0 AS distance
FROM restaurants
WHERE   OPEN = '1'
    AND STATUS = '1'
    AND is_delivery = '1'
    AND NAME LIKE '%chuck%'
ORDER BY distance LIMIT 0, 10
LEFT JOIN hours ON (restaurants.id = hours.restaurant_id AND hours.day_of_week = 'Tuesday')

但它只是让我在LEFT JOIN上犯了一个无用的错误。

  

“#1064 - 您的SQL语法出错;请查看与您的MySQL服务器版本对应的手册,以便在'LEFT JOIN hours ON'附近使用正确的语法(restaurants.id = hours.restaurant_id AND hours.day_of_week ='第1行“

2 个答案:

答案 0 :(得分:3)

我猜你在你的SQL语句结束时卡住了你的LEFT JOIN并且它吓坏了你(或类似的东西),但是因为你没有&很难说#39; t包括导致你在那里显示的错误的SQL语句。

查询中的所有联接都发生在SQL语句的FROM子句中。这是SQL语句的一部分,用于设置您选择的表/视图以及它们之间的关系。

无论如何,以下情况应该有效:

SELECT *,
    0 AS distance
FROM restaurants
LEFT JOIN hours ON
        restaurants.id = hours.restaurant_id
        AND hours.day_of_week = 'Tuesday'

WHERE
    OPEN = '1'
    AND STATUS = '1'
    AND is_delivery = '1'
    AND NAME LIKE '%chuck%'
ORDER BY distance 
LIMIT 0,10

有点奇怪的是,你在distance订购时始终为0,但也许有一个原因也没有说明。

答案 1 :(得分:0)

您的SQL请求应该看起来像

SELECT *, 0 AS distance FROM restaurants 
LEFT JOIN hours ON (restaurants.id = hours.restaurant_id AND hours.day_of_week = 'Tuesday')
WHERE open = '1' AND status = '1' AND is_delivery = '1' AND name LIKE '%chuck%' ORDER BY distance LIMIT 0, 10

JOIN来自FROM字段语句