[英]Sql for selecting from a table
我有一张这样的桌子
Id title parentId subparentId itemcategory
1 service cat1 0 0 C
2 service cat2 0 0 C
3 service subcat1 1 0 S
4 service subcat2 2 0 S
5 Item 1 1 0 I
5 Item 2 1 3 I
6 Item 3 2 4 I
我需要像这样的出局
service cat1
Item 1
service subcat1
Item 2
service cat2
service subcat2
Item 3
即,列表以升序顺序显示项目(类别,子类别,项目),如果项目具有任何子类别,则它应属于子类别
我想你应该尝试类似的东西:
SELECT
t1.title,
t2.title,
t3.title
FROM table t1
LEFT JOIN table t2 ON t1.id = t2.parentId
LEFT JOIN table t3 ON t2.id = t3.subparentId
WHERE t1.itemcategory = 'C'
AND t2.itemcategory = 'S'
AND t3.itemcategory = 'I'
;
对于这种情况:
你应该加入你的第三个表(项目),直接用第一个表(服务猫),而不是像我的例子中的第二个表。
这是一个复杂的问题,因为sql查询结果中只能有一个维度。
但我们可以在这里做一些小动作
SELECT *
FROM
(
SELECT
id,
title,
parentId,
subparentId,
itemcategory,
IF(
parentId = 0 AND subparentId = 0,
id * 10000,
IF(
subparentId = 0,
parentId * 10000 + 100 - id,
parentId * 10000 + subparentId * 100 + id
)
) AS itemOrder
FROM
table1
) allOrder
ORDER BY allOrder.itemOrder
SQL小提琴: http ://sqlfiddle.com/#!9/5f711/1/0
如果您有更多行,请增加乘数。
另一种方法: http : //sqlfiddle.com/#!9 / bbf4d / 1
(这里不需要乘数)
select
concat(indent1, indent2, title) as title
from (
select
if(parentid>0,parentid,id) as id1,
case itemcategory
when 'C' then -1
when 'S' then id
when 'I' then if(subparentid>0,subparentid,0)
end as id2,
case itemcategory
when 'C' then -1
when 'S' then -1
when 'I' then id
end as id3,
case itemcategory
when 'C' then ''
when 'S' then '- - '
when 'I' then '- - '
end as indent1,
case itemcategory
when 'C' then ''
when 'S' then ''
when 'I' then '- - '
end as indent2,
title
from table1
order by id1,id2,id3
) allitems
这段代码的一半用于缩进,因此您可以获得更好的视图。 它就像你要求的那样(即使它们不在同一级别,所有项目都是相同的缩进),但你可以自己动摇它。
您还可以在第一个选择中添加id1,id2,id3以查看订单的完成方式。 外部选择仅用于通过缩进单独查看标题。
结果将是:
title
----------------------
service cat1
- - - - Item 1
- - service subcat1
- - - - Item 2
service cat2
- - service subcat2
- - - - Item 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.