我这里有一点问题。有三个表:
表1
category_id parent_id
1 0
2 1
3 0
4 0
5 10
表2
category_id Name
1 Cars
2 Toys
3 Gifts
4 For women
5 For men
表3
product_id category_id
1 2
1 1
2 3
2 1
3 2
4 3
4 5
product_id列中的数字可以重复多次。 我想加入表格并将每个product_id排成一行,如下所示:
product_id category1 category2
1 Toys Cars
2 Gifts Cars
3 Toys Null
4 Gifts For men
parent_id 列包含指定类别类型和级别的数字,可以是主要类别也可以是子类别。这是我的代码,但我在
中得到0 SELECT product_to_category.product_id, sum(CASE(category.parent_id) WHEN 1
THEN category_description.name ELSE 0 END) as category1,
sum(CASE(category.parent_id) WHEN 2
THEN category_description.name ELSE 0 END) as category2
from category LEFT JOIN category_description ON
category_description.category_id = category.category_id
LEFT JOIN product_to_category ON category.category_id = product_to_category.category_id
group by category.category_id
当我执行它时,我在category_main列
上得到0值product_id category1 category2
1 0 0
2 0 0
3 0 0
4 0 0
答案 0 :(得分:1)
更改并检查
SELECT tab.product_id,
Sum(category_id1) AS Category_id1,
Sum(category_id2) AS Category_id2
INTO #temptable
FROM (SELECT a.product_id,
0 AS Category_id1,
Min(a.category_id) AS Category_id2
FROM #table3 a
INNER JOIN (SELECT product_id,
Count(category_id) AS Category_id
FROM #table3
GROUP BY product_id
HAVING Count(category_id) > 1) b
ON a.product_id = b.product_id
GROUP BY a.product_id
UNION ALL
SELECT a.product_id,
Max(a.category_id) AS Category_id1,
0 AS Category_id2
FROM #table3 a
INNER JOIN (SELECT product_id,
Count(category_id) AS Category_id
FROM #table3
GROUP BY product_id
HAVING Count(category_id) > 1) b
ON a.product_id = b.product_id
GROUP BY a.product_id
UNION ALL
SELECT a.product_id,
a.category_id AS Category_id1,
0 AS Category_id2
FROM #table3 a
INNER JOIN (SELECT product_id,
Count(category_id) AS Category_id
FROM #table3
GROUP BY product_id
HAVING Count(category_id) <= 1) b
ON a.product_id = b.product_id) tab
GROUP BY tab.product_id
SELECT #temptable.product_id,
CAT1.name AS Category_id1,
CAT2.name AS Category_id2
FROM #temptable
LEFT OUTER JOIN #table2 CAT1
ON #temptable.category_id1 = CAT1.category_id
LEFT OUTER JOIN #table2 CAT2
ON #temptable.category_id2 = CAT2.category_id
答案 1 :(得分:1)
为什么不使用COUNT()和WHERE?你想要计算category.parent_id等于1的数量,对吧?所以:
SELECT category.category_id, COUNT(category_description.name)
category_main FROM category
LEFT JOIN category_description
ON category_description.category_id = category.category_id
WHERE category.parent_id = 1
GROUP BY category.category_id;
答案 2 :(得分:0)
SELECT
category.category_id,
category_main = CASE
WHEN category.parent_id = 1
THEN category_description.name
ELSE '0'
END
FROM category
LEFT JOIN category_description ON
category_description.category_id = category.category_id
答案 3 :(得分:0)
您是否需要不同列中的每个类别?
如果您不需要,请使用group_concat
就是这样:
SELECT t3.product_id, GROUP_CONCAT(t2.name) FROM table3 t3
LEFT JOIN table2 t2 on t2.category_id = t3.category_id
LEFT JOIN table1 t1 on t1.parent_id = t2.category_id
GROUP BY t3.product_id