我有一个表格,其中包含如下所示的设置列表:
CREATE TABLE `widget_settings` (
`setting_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`widget_id` INT(10) UNSIGNED NOT NULL,
`setting_parent` INT(10) UNSIGNED NOT NULL DEFAULT '0',
`setting_name` CHAR(50) NOT NULL,
`setting_type` CHAR(50) NOT NULL,
`setting_default` CHAR(50) NOT NULL,
PRIMARY KEY (`setting_id`)
)
我想按setting_name
订购行,有些设置有子项,因此在设置列表后,它的子项和子项的名称为setting_parent
,所以基本上我想要的输出看起来像这样:
setting_name | setting_id | setting_parent
-------------------------------------------------------
A | 1 | 0
B | 2 | 0
YA | 4 | 2
YB | 5 | 2
C | 20 | 0
ZA | 25 | 20
我希望这会有效,但它没有:
select * from widget_settings
where widget_id = 1
order by setting_name, setting_parent
以下是SQLFiddle
答案 0 :(得分:1)
select a.*
from widget_settings a
left join widget_settings b
on b.widget_id = a.widget_id
and b.setting_id = a.setting_parent
where a.widget_id = 1
order by
ifnull(b.setting_name, a.setting_name),
if(b.setting_name is null, '', a.setting_name)
上进行测试
这里是如何构建order by
的:
A ''
B ''
B YA <-- parent name goes to first position & children name to second
B YB
C ''
C ZA
答案 1 :(得分:0)
我认为这可能适用于一个级别。该概念可以应用于N个级别,但每个级别都添加左连接。并进一步使订单复杂化。
它基本上将widget_Settings连接到自身,并将父名称连接到子级。例如:
Setting_ID 2,4,5将成为
B - 2
BYA - 4
BYB - 5
然而这是未经测试的......
SELECT P.setting_Name, P.Setting_Id, P.Setting_parent
FROM widget_Settings P
LEFT JOIN widget_Settings C
on C.Setting_Parent = P.Setting_ID
ORDER BY CONCAT(P.Setting_name,coalesce(C.Setting_name,''))