我有这张桌子:
表1
--------------------
id | category
--------------------
1 | Cat1
2 | Cat2
3 | Cat3
对于每个类别,我都有包含子类别的表格和相应的类别ID,如下所示:
表2
--------------------------------
id | subcategory | category_id
--------------------------------
1 | subcat1 | 1
2 | subcat2 | 1
3 | subcat3 | 1
4 | subcat4 | 1
表3
--------------------------------
id | subcategory | category_id
--------------------------------
1 | subcat5 | 2
2 | subcat6 | 2
3 | subcat7 | 2
4 | subcat8 | 2
我想查询我的数据,所以我得到以下内容:
-----------------------------------------------------
category | subcategory ( from Table2 and Table3)
-----------------------------------------------------
Cat1 | subcat1
Cat1 | subcat2
Cat1 | subcat3
Cat1 | subcat4
Cat2 | subcat5
Cat2 | subcat6
Cat2 | subcat7
Cat2 | subcat8
Cat3 | NULL
我尝试过类似的东西,但是它将每个表中的数据放在一个新列上。
SELECT Table1.category, Table2.subcategory , Table3.subcategory
FROM Table1
LEFT JOIN Table2 ON Table1.id=Table2 .category_id
LEFT JOIN Table3 ON Table1.id=Table3.category_id
我是初学者。
谢谢!
答案 0 :(得分:1)
每个子类别都不需要新表。如果你改变它,你只有两个表,只需加入它们。
答案 1 :(得分:1)
SELECT c.Category,s.SubCategory
FROM Table1 c
LEFT JOIN
(
SELECT * FROM Table2
UNION ALL
SELECT * FROM Table3
) s
ON c.id = s.id;
答案 2 :(得分:1)
当我从你的问题中读到子类别在不同的表中时,你可以为这些表创建一个UNION(ALL),然后加入你的Table1,就像这样
SELECT Table1.category, Table2.subcategory, Table3.subcategory
FROM Table1
LEFT JOIN (SELECT Table2.category_id, Table2.subcategory
FROM Table2
UNION ALL
SELECT Table3.category_id, Table3.subcategory
FROM Table3
) sub
ON Table1.id=sub.category_id
希望这有助于你
答案 3 :(得分:0)
建议:创建一些VIEW
以确保您具有合理且一致的数据项,这将使查询更容易编写,例如
CREATE VIEW Subcategories
AS
SELECT subcategory, category_id
FROM Table2
UNION
SELECT subcategory, category_id
FROM Table3;
CREATE VIEW Categories
AS
SELECT id AS category_id, category
FROM Table1;
SELECT category, subcategory
FROM Categories NATURAL JOIN Subcategories
UNION
SELECT category, 0 AS subcategory
FROM Categories
WHERE category_id NOT IN ( SELECT category_id
FROM Subcategories );