此sql请求中的语法错误在哪里?

uhry853o  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(267)

我在附近发现一个语法错误 WHERE tbkay.keyword = 'ipsum' 在以下请求中(使用phpmyadmin):

SELECT tbart.articles_id FROM articles AS tbart
    LEFT JOIN keywords AS tbkey 
    LEFT JOIN articles_keyword AS tbjoin 
        ON tbart.articles_id = tbjoin.articles_id 
        AND tbkey.id = tbjoin.keywords_id
    WHERE tbkey.keyword = 'ipsum'


我不明白。

neekobn8

neekobn81#

每个 JOIN 应该有相应的 ON 条款:

SELECT tbart.articles_id
FROM articles tbart LEFT JOIN
     articles_keyword tbjoin 
     ON tbart.articles_id = tbjoin.articles_id LEFT JOIN
     keywords tbkey 
     ON tbkey.id = tbjoin.keywords_id
WHERE tbkey.keyword = 'ipsum' ;

你的版本有两个 JOIN s和1 ON ,因此出现错误。

yptwkmov

yptwkmov2#

您没有使用 ON 每次联接后的子句:

SELECT tbart.articles_id 
FROM articles AS tbart
INNER JOIN articles_keyword AS tbjoin ON tbart.articles_id = tbjoin.articles_id 
INNER JOIN keywords AS tbkey ON tbkey.id = tbjoin.keywords_id
WHERE tbkey.keyword = 'ipsum'

我还将连接更改为 INNER 加入是因为 WHERE 子句只返回匹配的行。
如果你想保留 LEFT 联接并返回 articles 必须将此条件移到 ON 条款:

SELECT tbart.articles_id 
FROM articles AS tbart
LEFT JOIN articles_keyword AS tbjoin ON tbart.articles_id = tbjoin.articles_id 
LEFT JOIN keywords AS tbkey ON tbkey.id = tbjoin.keywords_id AND tbkey.keyword = 'ipsum'

相关问题