programing

다른 테이블에서 ID가 있는 행 선택

procenter 2022. 9. 24. 22:05
반응형

다른 테이블에서 ID가 있는 행 선택

이 테이블이라고 부르자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이 경우 2개의 쿼리가 필요합니까?아니면 이 쿼리가 필요합니까?join스테이트먼트?

다음을 시도해 보십시오(서브쿼리).

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"

2개의 테이블에서 모든 필드를 수신하는 경우:

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"

서브쿼리를 사용할 수 있습니다.

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'
SELECT terms.*
FROM terms JOIN terms_relation ON id=term_id
WHERE taxonomy='categ'

언급URL : https://stackoverflow.com/questions/10562915/selecting-rows-with-id-from-another-table

반응형