mysql 父级查询子元素_MySQL:如何查询父级子元素?

这是一个想法。但它基于对数据设置方式的许多假设。不断增加的树下ID,只有两个级别,等等。

SELECT f.foo_id,f.foo_parent_id FROM foo f

foo f- 给我前面的X个parent_id

(这很好,你只需调整LIMIT 10来改变显示的父级别数)

INNER JOIN

(select foo_id from foo where foo_parent_id is null order by foo_parent_id

LIMIT 10

) top_foo_parent

on isnull(f.foo_parent_id,f.foo_id) = top_foo_parent.foo_id

WHERE(这部分是一种hacky,因为你必须把更长的一串这些来过两个子元素)

- 这是第一个子元素,或者......

(f.foo_id in (select MIN(foo_id) from foo fc1 where fc1.foo_parent_id =f.foo_parent_id)

)

or- 这是第二个子元素,或者......

(f.foo_id in (select MIN(foo_id) from foo fc1 where fc1.foo_parent_id =f.foo_parent_id and fc1.foo_id not in (select MIN(foo_id) from foo fc2 where fc2.foo_parent_id=f.foo_parent_id))

)

or- 是父级

f.foo_parent_id is null

order by isnull(f.foo_parent_id,f.foo_id)*100 + f.foo_id所以我们在这里做的基本上是通过parent_id列进行排序,然后是略微扭曲的下面的子列。如果parentid列为NULL,那么我们使用实际ID。这意味着为了订购目的,我们的表格如下所示:

==============================================================================

| foo_id | foo_parent_id | isnull(f.foo_parent_id,f.foo_id)

==============================================================================

| 1 | NULL | (1)

| 2 | NULL | (2)

| 3 | 1 | 1

| 4 | 2 | 2

| 5 | 1 | 1

| 7 | 2 | 2

----------------------------------------------------------------------然后我们将该排序列乘以* 100

==============================================================================

| foo_id | foo_parent_id | isnull(f.foo_parent_id,f.foo_id)*100

==============================================================================

| 1 | NULL | 100

| 2 | NULL | 200

| 3 | 1 | 100

| 4 | 2 | 200

| 5 | 1 | 100

| 7 | 2 | 200

----------------------------------------------------------------------最后我们将foo_id列添加到它

==============================================================================

| foo_id | foo_parent_id | isnull(f.foo_parent_id,f.foo_id)*100 + foo_id

==============================================================================

| 1 | NULL | 101

| 2 | NULL | 202

| 3 | 1 | 103

| 4 | 2 | 204

| 5 | 1 | 105

| 7 | 2 | 207

----------------------------------------------------------------------现在我们按该虚拟列顺序排序表...

==============================================================================

| foo_id | foo_parent_id | ORDER BY isnull(f.foo_parent_id,f.foo_id)*100 + foo_id

==============================================================================

| 1 | NULL | 101

| 3 | 1 | 103

| 5 | 1 | 105

| 2 | NULL | 202

| 4 | 2 | 204

| 7 | 2 | 207

----------------------------------------------------------------------我们去!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值