[英]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.