我有三个表:
表1-文档:
ID Title
====================
1 doc 1
2 doc 2
3 doc 3
4 doc 4
每个文档可以分配给多个子类别-此关系位于表2中。
表2-与document_id和subcategory_id相匹配的doc_subcategory:
document_id subcategory_id
============================
1 1
1 2
1 5
2 1
2 2
3 1
3 7
4 2
4 3
4 5
表3-子类别-还有一个子类别表,其中包含其ID,名称和另一个(较高)类别级别的higer_level_category_id。
id name higer_level_category_id
============================================
1 To buy 1
2 To give back 1
3 To send 1
4 To buy 2
5 To send 2
6 To throw 2
7 To destroy 2
想要得到的是这个
doc_id doc_title subcat_id subcat_id upper_1 upper_2
for_upper_cat1 for_upper_cat2
==========================================================================================
1 doc 1 1,2 5 1 2
2 doc 2 1,2 NULL 1 NULL
3 doc 3 1,7 7 1 2
4 doc 4 2,3 5 1 2
我创建了这种查询,但是我不知道如何将子类别和较高类别分隔为单独的列:
SELECT
documents.id as doc_id,
documents.title as doc_title,
group_concat(DISTINCT doc_subcategory.subcategory_id) as subcat_id,
group_concat(DISTINCT subcategories.higer_level_category_id) as upper
FROM
documents
LEFT JOIN
doc_subcategory
ON
(
documents.id = doc_subcategory.id
)
LEFT JOIN
subcategories
ON
(
doc_subcategory.subcategory_id = subcategories.id
)
GROUP BY documents.id;
我注意到,当我给order by子句的另一个参数是subcategories.higer_level_category_id时,这给我带来了更好的结果,但这仍然远非我想要的。问题在于动态列应该动态创建,该动态列与子类别的数量有关。higer_level_category_id。
答案 0 :(得分:0)
您的查询中似乎有一些错误(例如,没有列doc_subcategory.id
)。我将一些rextester-demo与您的查询放在一起。您可以在这里找到它: http://rextester.com/XOP97169
我将您的查询更新为
SELECT
documents.id as doc_id,
documents.title as doc_title,
group_concat(DISTINCT doc_subcategory.subcategory_id) as subcat_id,
group_concat(DISTINCT subcategories.higher_level_category_id) as upper
FROM documents
LEFT JOIN doc_subcategory ON documents.id = doc_subcategory.document_id
LEFT JOIN subcategories ON doc_subcategory.subcategory_id = subcategories.id
GROUP BY documents.id;
这导致
doc_id doc_title subcat_id upper
--------------------------------------
1 doc 1 1,2,5 1,2
2 doc 2 1,2 1,2
3 doc 3 1,7 1,2
4 doc 4 2,3,5 2,3
也许您可以在此小提琴的基础上举例说明一些更好的观点。但是,正如@Strawberry已经说过的那样,数据的“表示”通常应该留给您的嵌入式应用程序,无论是JavaScript(node.js),python,c#还是php。...