根据其他两个表获取一行

时间:2012-05-13 11:18:50

标签: mysql sql

对于一个实例,我们有这三个表:

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_idsamsung的所有行?

所以它必须得到:nokiaopera(不是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  |
+---------+

上面不需要的查询输出:

{{1}}

2 个答案:

答案 0 :(得分:1)

您应该只是在JOIN内移动条件。此外,在WHERE中移动post_id条件似乎更合乎逻辑:

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

答案 1 :(得分:0)

这是一个没有连接的版本:

SELECT name FROM terms WHERE id IN 
(SELECT id FROM terms_taxonomy,terms_relation,terms
 WHERE terms_relation.post_id = 1 
 AND terms_taxonomy.taxonomy = "categ" 
 AND terms.id = terms_taxonomy.term_id);