例如,我们有这三个表:
terms_relation
╔═════════╦═════════╗
║ post_id ║ term_id ║
╠═════════╬═════════╣
║ 1 ║ 1 ║
║ 1 ║ 2 ║
║ 1 ║ 3 ║
╚═════════╩═════════╝
terms_taxonomy
╔════╦═════════╦══════════╗
║ id ║ term_id ║ taxonomy ║
╠════╬═════════╬══════════╣
║ 1 ║ 1 ║ categ ║
║ 2 ║ 2 ║ categ ║
║ 3 ║ 3 ║ tag ║
║ 4 ║ 3 ║ categ ║
║ 5 ║ 4 ║ categ ║
║ 6 ║ 5 ║ tag ║
╚════╩═════════╩══════════╝
条款
╔════╦════════╦════════╗
║ id ║ name ║ slug ║
╠════╬════════╬════════╣
║ 1 ║ samsung║ samsung║
║ 2 ║ nokia ║ nokia ║
║ 3 ║ opera ║ opera ║
║ 4 ║ chrome ║ chrome ║
║ 5 ║ webkit ║ webkit ║
╚════╩════════╩════════╝
当 terms_relation.post_id = 1
, 如何选择 terms
中的所有行它有一个 taxonomy
的 categ
在 terms_taxonomy
基于 term_id
?
所以它必须得到:samsung
, nokia
(不是 opera
,因为它是一个标签)。
这是我目前的尝试,不幸的是我不明白我的查询有什么问题:
select terms.name from terms_taxonomy
join terms_relation
on terms_relation.post_id = 1
join terms
on terms_taxonomy.term_id = terms.id
where taxonomy = "categ"
上面查询的意外输出:
+---------+
| name |
+---------+
| samsung |
| nokia |
| opera |
| chrome |
| samsung |
| nokia |
| opera |
| chrome |
| samsung |
| nokia |
| opera |
| chrome |
| samsung |
| nokia |
| opera |
| chrome |
| samsung |
| nokia |
| opera |
| chrome |
| samsung |
| nokia |
| opera |
| chrome |
+---------+
最佳答案
您应该只将条件移动到 JOIN
中。此外,将 post_id
条件移动到 WHERE 中似乎更符合逻辑:
SELECT t.name
FROM terms_relation tr
JOIN terms_taxonomy tt ON tr.term_id = tt.term_id AND tt.taxonomy = "categ"
JOIN terms t ON tr.term_id = tt.id
WHERE tr.post_id = 1
编辑 我再次阅读了您的问题,但无法真正弄清楚关系是如何定义的,我假设这些连接条件:
- terms_taxonomy.term_id = terms_relation.term_id
- terms.id = terms_taxonomy.term_id
关于mysql - 根据其他两个表获取一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10571284/