2012-11-25 2 views
0

나는 여전히 SQL- 신참이다. 주어진 구조의 테이블이 3 개 있습니다.mysql에 세 개의 테이블, 하나는 관계 테이블 쿼리

table1 (products) 
-------------------------------------- 
id ident title types desc 
-------------------------------------- 
01 111ab title1 2  details 1 
02 222ab title2 1  details 2 
03 333ab title3 2  details 3 

제품은 많은 제품 유형에 속할 수 있습니다. "types"-column은 제품과 관련된 유형의 수입니다. "111ab"제품은 2 가지 제품 유형에 속합니다.

table2 (product-types) 
-------------------------- 
id type typedesc 
-------------------------- 
01 type1 description 1 
02 type2 description 2 
03 type3 description 3 


table3 (relations) 
------------------- 
id tbl1id tbl2id 
------------------- 
01 01  01 
02 02  03 
03 03  03 
04 01  03 
05 03  02 

표 3은 table1 (제품)과 table2 (제품 유형) 간의 관계를 보여줍니다. 제품 "111ab"는 제품 유형 "01"및 "03"과 관련됩니다.

나는 이런 식으로 뭔가해야 데이터 구조를 만들려면 :

type-description prod title desc 
------------------------------------------- 
type1-description1 111ab title1 details1 
type2-description2 333ab title3 details3 
type3-description3 111ab title1 details1 
type3-description3 222ab title2 details2 
type3-description3 333ab title3 details3 

ASSOC - 하위 배열과 관련된 제품과 제품 종류의 ASSOC 배열에 끝날 것이 구조 , 표 1의 "식별자"로 분류 :

type1 description1 
     111ab title1 details1 

type2 description2 
     333ab title3 details3 

type3 description3 
     111ab title1 details1 
     222ab title2 details2 
     333ab title3 details3 

이 배열 JSON 인코딩 및 AJAX 요청의 질의 결과로서 송신한다.

여기서 stackingflow에서 JOINing 테이블에 대한 스레드를 읽었지만 작동하는 SELECT 구조를 생성 할 수 없습니다. 단일 쿼리로는이 작업을 수행 할 수 없습니다. 나는 모른다.

제발, 아무도 나에게 약간의 도움을 줄 수 있습니까?

답변

2

INNER JOIN 요구 사항을 충분합니다,

SELECT a.type, a.typedesc, 
     c.ident, c.title, 
     c.`desc` 
FROM `product-types` a 
     INNER JOIN relations b 
      ON a.id = b.tbl2id 
     INNER JOIN products c 
      ON b.tbl1id = c.id 
ORDER BY a.type, a.typedesc 

또는

SELECT CONCAT(a.type, '-',a.typedesc) `type-description`, 
     c.ident, c.title, 
     c.`desc` 
FROM `product-types` a 
     INNER JOIN relations b 
      ON a.id = b.tbl2id 
     INNER JOIN products c 
      ON b.tbl1id = c.id 
ORDER BY `type-description` 
+0

예, 훌륭합니다. 결과는 필요한만큼입니다. 정말 고맙습니다. 바이올린 링크에 감사드립니다. – Tribun