0

私はまだ SQL 初心者です。特定の構造を持つ 3 つのテーブルがあります。

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

製品は、多くの製品タイプに属することができます。「タイプ」列は、製品に関連するタイプの数です。製品 "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 は、表 1 (製品) と表 2 (製品タイプ) の関係を示しています。製品 "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

この構造は、table1 の「ident」でソートされた、関連する製品を assoc-sub-array として持つ製品タイプの assoc-array になります。

type1 description1
        111ab title1 details1

type2 description2
        333ab title3 details3

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

この配列は json エンコードされ、ajax リクエストのクエリ結果として送信されます。

ここのstackoverflowでJOINingテーブルに関するスレッドを読みましたが、機能するSELECT構造を生成できません。たぶん、これは単一のクエリでは実行できません。知らない。

お願いします、誰か助けてくれませんか?

4

1 に答える 1

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`
于 2012-11-25T13:30:54.023 に答える