簡體   English   中英

用三個表查詢mysql,一個是關系表

[英]Query mysql with three tables, one is relation table

我還是一個SQL新手。 我有三個具有給定結構的表:

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顯示了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-sub-arrays,按table1的“ident”排序:

type1 description1
        111ab title1 details1

type2 description2
        333ab title3 details3

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

該數組將被json編碼並作為ajax-request的查詢結果發送。

我在stackoverflow上閱讀了有關JOINing表的線程,但無法生成有效的SELECT結構。 也許這不能通過單個查詢來完成。 我不知道。

拜托,有人能給我一點幫助嗎?

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`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM