当我的高亮表中出现slug时,我需要从文章和用户表中获取行。
Highlight Table
id | slug
1 blue
2 green
Article Table
id | slug | title
1 blue
2 pink
User Table
id | slug | name
1 blue
2 green
3 brown
继承我的疑问:
SELECT slug from highlight_table
INNER JOIN article_table ON highlight_table.slug = article_table.slug
INNER JOIN user_table ON highlight_table.slug = user_table.slug
我希望从文章表中获取id 1,从users表中获取id 1和2。
问题是我从查询中得不到任何回报。
答案 0 :(得分:1)
查询出错,因为SELECT slug
不明确。您的列slug
出现在所有表中,因此MySQL不知道要返回哪一列。你需要做
SELECT `highlight_table`.`slug` from `highlight_table`
这将告诉MySQL只返回slug
中的highlight_table
列。
然后你应该只获得1行蓝色,因为蓝色存在于所有三个表中。将文章和用户表格更改为LEFT JOIN
会得到2个结果(绿色和蓝色),因为INNER JOIN
基本上用作AND,而LEFT JOIN
更像是OR
更新!
根据最后的大量信息,这是一个有效的查询:
SELECT highlight.slug from highlight
LEFT JOIN article ON highlight.slug = article.slug
LEFT JOIN user ON highlight.slug = user.slug
WHERE
article.slug IS NOT NULL OR user.slug IS NOT NULL
这样做的另一个例子:
SELECT `highlight`.`slug` from `highlight`
WHERE `highlight`.`slug` IN (SELECT `user`.`slug` FROM `user` UNION SELECT `article`.`slug` FROM `article`)
OR
SELECT `highlight`.`slug` from `highlight`
INNER JOIN (SELECT `user`.`slug` FROM `user` UNION SELECT `article`.`slug` FROM `article`) AS `allslugs` ON `highlight`.`slug` = `allslugs`.`slug`
另一个更新,我将此称为“有趣的加入”
SELECT `highlight`.`slug` from `highlight`
RIGHT JOIN `user` ON `highlight`.`slug` = `user`.`slug`
LEFT JOIN `article` ON `highlight`.`slug` = `article`.`slug`
WHERE
`highlight`.`slug` IS NOT NULL
答案 1 :(得分:0)
尝试更改查询以限定选择列表中的列名
SELECT h.`slug` from HighlightTable h
INNER JOIN ArticleTable a ON h.`slug` = a.`slug`
INNER JOIN UserTable u ON h.`slug` = u.`slug`;
无法重现此问题。见This Fiddle
根据您的最新评论,您需要LEFT JOIN
查询,例如
SELECT h.`slug` from HighlightTable h
LEFT JOIN ArticleTable a ON h.`slug` = a.`slug`
LEFT JOIN UserTable u ON h.`slug` = u.`slug`;
然后单独执行JOIN
和UNION
结果集
SELECT h.`slug` from HighlightTable h
INNER JOIN ArticleTable a ON h.`slug` = a.`slug`
UNION
SELECT h.`slug` from HighlightTable h
INNER JOIN UserTable u ON h.`slug` = u.`slug`;