我正在尝试执行一个PHP MySQL查询...它具有带有类别和子类别的项目列表。我想按字母顺序对列表进行排序,但列表中包含类别(及其包含的项)。例如...
有三个表... 类别表(项目猫)...
> itemcat catname
> 1 AGeneralCategory
> 2 Food
> 3 Clothing
子类别表(itemsubcats)和父类别的列(itemcat)...
> itemsubcat itemcat subcatname
> 1 2 Fruit
> 2 2 Vegetables
> 3 2 Meat
> 4 3 Shoewear
> 5 3 Hats
然后是各个项目(项目)的表格。...
> itemid itemname itemcat itemsubcat
> 1 Apples 2 1
> 2 Sneakers 3 4
> 3 Onion 2 2
> 4 Banana 2 1
> 5 Steak 2 3
> 6 Sombrero 3 5
> 7 Sandals 3 4
> 8 Jeep 1 null
> 9 Baseball Cap 3 5
> 10 Mountain 1 null
> 11 Bread 2 null
> 12 Veggiemite 2 null
和预期的结果。 注意:我可能可以使用PHP添加类别/子类别名称,但是我需要按如下顺序排列各个项目的列表...
> [AGeneralCategory]
> Jeep
> Mountain
> [Clothing]
> [Headwear]
> Baseball Cap
> Sombrero
> [Shoewear]
> Sandals
> Sneakers
> [Food]
> Bread
> [Fruit]
> Apple
> Banana
> [Meat]
> Steak
> Veggiemite
> [Vegetables]
> Onion
到目前为止,我已经尝试了一些JOINS ...但是似乎无法获得理想的结果...这是我目前拥有的...
SELECT a1.itemid iid, a1.itemname iname, a1.itemcat icat, a1.itemsubcat isub
FROM items a1
LEFT
JOIN itemcats b1
ON a1.itemcat = b1.itemcat
LEFT
JOIN itemsubcats c1
ON a1.itemsubcat = c1.itemsubcat
ORDER
BY a1.itemcat, a1.itemsubcat
更新:这是决赛,这似乎很棒。...
SELECT a.itemid,
a.itemname,
a.itemcost,
a.itemcostcoin,
a.itemweight,
a.itemdesc,
a.itemcat,
b.catname,
a.itemsubcat,
c.subcatname
FROM (SELECT
itemid,
itemcat,
itemsubcat,
itemname,
itemcost,
itemcostcoin,
itemweight,
itemdesc
FROM items
UNION SELECT itemsubcat,
NULL AS itemcat,
NULL AS itemsubcat,
subcatname,
NULL AS itemcost,
NULL AS itemcostcoin,
NULL AS itemweight,
NULL AS itemdesc
FROM itemsubcats)
AS a
LEFT JOIN itemcats b ON a.itemcat=b.itemcat
LEFT JOIN itemsubcats c ON a.itemsubcat=c.itemsubcat
WHERE a.itemcat='1'
答案 0 :(得分:0)
您需要更正order by子句,并使用类别和子类别的名称而不是其ID
SELECT
b1.catname as catname,
c1.subcatname as subcatname ,
a1.itemid as iid,
a1.itemname as iname
FROM items a1
LEFT JOIN itemcats b1 ON a1.itemcat=b1.itemcat
LEFT JOIN itemsubcats c1 ON a1.itemsubcat=c1.itemsubcat
ORDER BY b1.catname, c1.subcatname
对于树形视图,您可以在应用程序层(PHP)中转换此数据