如何离开加入另一个嵌套表?
第一个查询,
SELECT *
FROM category AS a
WHERE a.type = 'content'
结果,
category_id type code
1 content content_1
2 content content_2
3 content content_3
第二个查询,
SELECT*
FROM content AS c
LEFT JOIN article_has_content AS x
ON x.content_id = c.content_id
WHERE x.article_id = '4'
结果,
category_id value article_id
1 xxa 4
2 xxb 4
我追求的结果,
category_id type code value
1 content content_1 xxa
2 content content_2 xxb
3 content content_3 NULL
第三个查询,
SELECT*
FROM
(
SELECT *
FROM category AS a
WHERE a.type = 'content'
) a
LEFT JOIN b
(
SELECT*
FROM content AS c
LEFT JOIN article_has_content AS x
ON x.content_id = c.content_id
WHERE x.article_id = '4'
) b
ON b.category_id = a.category_id
误差,
1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以获得正确的语法
附近'( 选择* 来自内容AS c
LEFT JOIN article_has_content AS x ON x.content' at line 9
答案 0 :(得分:1)
你几乎是对的:
SELECT *
FROM
(
SELECT *
FROM category AS a
WHERE a.type = 'content'
) a
LEFT JOIN -- the alias name here was wrong
(
SELECT*
FROM content AS c
LEFT JOIN article_has_content AS x
ON x.content_id = c.content_id
WHERE x.article_id = '4'
) b -- and you had the alias already here at the right position
ON b.category_id = a.category_id
答案 1 :(得分:1)
您将别名放在子查询之后。但总的来说,您的查询过于复杂。我认为这样做你想要的:
SELECT c.category_id, c.type, c.code, con.value
FROM category c left join
content con
on c.category_id = con.category_id left join
article_has_content ahc
on con.content_id = ahc.content_id and
ahc.article_id = '4';
答案 2 :(得分:-1)
如何组合这两个查询,如下所示:
SELECT*
FROM content AS c
LEFT JOIN article_has_content AS x
ON x.content_id = c.content_id
LEFT JOIN category a ON a.category_id = c.category_id AND a.type = 'content'
WHERE x.article_id = '4'