小编典典

从另一个表中选择具有ID的行

sql

我们将此表称为terms_relation

+---------+----------+-------------+------------+------------+--+
| term_id | taxonomy | description | created_at | updated_at |  |
+---------+----------+-------------+------------+------------+--+
|       1 | categ    | non         | 3434343434 |   34343433 |  |
|       2 | categ    | non         | 3434343434 | 3434343434 |  |
|       3 | tag      | non         | 3434343434 | 3434343434 |  |
|       4 | tag      | non         | 3434343434 | 3434343434 |  |
+---------+----------+-------------+------------+------------+--+

这是表terms

+----+-------------+-------------+
| id |    name     |    slug     |
+----+-------------+-------------+
|  1 | hello       | hello       |
|  2 | how are you | how-are-you |
|  3 | tutorial    | tutorial    |
|  4 | the end     | the-end     |
+----+-------------+-------------+

我该如何选择表中的所有行terms和表terms_relation它的表分类terms_relationcateg?我需要两个查询还是可以使用一条join语句?


阅读 159

收藏
2021-03-17

共1个答案

小编典典

试试这个(子查询):

SELECT * FROM terms WHERE id IN 
   (SELECT term_id FROM terms_relation WHERE taxonomy = "categ")

或者,您可以尝试以下操作(JOIN):

SELECT t.* FROM terms AS t 
   INNER JOIN terms_relation AS tr 
   ON t.id = tr.term_id AND tr.taxonomy = "categ"

如果要从两个表中接收所有字段:

SELECT t.id, t.name, t.slug, tr.description, tr.created_at, tr.updated_at 
  FROM terms AS t 
   INNER JOIN terms_relation AS tr 
   ON t.id = tr.term_id AND tr.taxonomy = "categ"
2021-03-17