我已經使用分層數據模式來存儲數據庫中的產品。產品只有主要和子類別,這是我檢索完整產品樹時的結果。如何使用mysql在分層數據模式中創建此SELECT?
SELECT t1.name AS lev1,
t2.name as lev2,
t3.name as lev3,
FROM categories AS t1
LEFT JOIN categories AS t2
ON t2.parent = t1.category_id
LEFT JOIN categories AS t3
ON t3.parent = t2.category_id
WHERE t1.name = 'Products'
+----------+----------------------+-------------------+
| lev1 | lev2 | lev3 |
+----------+----------------------+-------------------+
| Products | Computers | Laptops |
| Products | Computers | Desktop Computers |
| Products | Computers | Tab PCs |
| Products | Computers | CRT Monitors |
| Products | Computers | LCD Monitors |
| Products | Computers | LED Monitors |
| Products | Mobile Phones | LG Phone |
| Products | Mobile Phones | Anroid Phone |
| Products | Mobile Phones | Windows Mobile |
| Products | Mobile Phones | iPad |
| Products | Mobile Phones | Samsung Galaxy |
| Products | Digital Cameras | test |
| Products | Printers and Toners | NULL |
| Products | test | abc |
| Products | test2 | NULL |
| Products | test3 | NULL |
| Products | Computer Accessaries | USB Cables |
| Products | Computer Accessaries | Network Cables |
+----------+----------------------+-------------------+
我的問題是我需要選擇level2和level3類別ID以及此選擇查詢。
我想它是這樣的:
SELECT t1.name AS lev1,
t2.name as lev2,
t3.name as lev3,
t3.category_id
FROM categories AS t1
LEFT JOIN categories AS t2
ON t2.parent = t1.category_id
LEFT JOIN categories AS t3
ON t3.parent = t2.category_id
WHERE t1.name = 'Products'
但其只提供3級標識。喜歡這個。
+----------+----------------------+-------------------+-------------+
| lev1 | lev2 | lev3 | category_id |
+----------+----------------------+-------------------+-------------+
| Products | Computers | Laptops | 3 |
| Products | Computers | Desktop Computers | 4 |
| Products | Computers | Tab PCs | 5 |
| Products | Computers | CRT Monitors | 6 |
| Products | Computers | LCD Monitors | 7 |
| Products | Computers | LED Monitors | 8 |
| Products | Mobile Phones | LG Phone | 10 |
| Products | Mobile Phones | Anroid Phone | 11 |
| Products | Mobile Phones | Windows Mobile | 12 |
| Products | Mobile Phones | iPad | 13 |
| Products | Mobile Phones | Samsung Galaxy | 14 |
| Products | Digital Cameras | test | 21 |
| Products | Printers and Toners | NULL | NULL |
| Products | test | abc | 20 |
| Products | test2 | NULL | NULL |
| Products | test3 | NULL | NULL |
| Products | Computer Accessaries | USB Cables | 23 |
| Products | Computer Accessaries | Network Cables | 24 |
+----------+----------------------+-------------------+-------------+
有人可以告訴我怎樣才能同時獲得level2和level3?
你解決問題了嗎? –