mysql - 根据其他两个表获取一行

标签 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 中的所有行它有一个 taxonomycategterms_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/

相关文章:

mysql - 对于支持事务的 Node.js 和 MariaDB,我应该使用哪种 ORM?

mysql - 为什么我的图像存储为 MySQL longblobs 仅部分显示?

sql - 如何将参数列表传递给存储过程并在 SQL Server 中执行批量插入

使用分号和撇号的 SQL 崩溃

php - MYSQL 查询最近的条目

mysql - 需要一种简单的方法从列中提取电子邮件

通过 SSH 隧道进行 MySQL 复制

MySQL 错误 1442 : Cannot update a table in a trigger/stored procedure

sql - 从DB2中的查询创建定界字符串

sql - 大型SELECT查询似乎向相同但较小的SELECT查询返回不同的顺序?