52

我们称这个表为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语句?

4

3 回答 3

104

试试这个(子查询):

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

或者你可以试试这个(加入):

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"
于 2012-05-12T10:36:07.343 回答
26

您可以使用子查询:

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

如果您需要显示两个表中的所有列:

SELECT t.*, tr.*
FROM terms t, terms_relation tr
WHERE t.id = tr.term_id
AND tr.taxonomy='categ'
于 2012-05-12T10:35:50.373 回答
3
SELECT terms.*
FROM terms JOIN terms_relation ON id=term_id
WHERE taxonomy='categ'
于 2012-05-12T10:36:52.477 回答