我有一个表:用户
表字段:
user_id PK INT AI user_name VARCHAR (45) parent_user_id FK INT
Rows:
user_id user_name parent_user_id
1 dave 0
2 john 1
3 pritesh 1
4 larry 3
5 abha 4
请创建一个查询,告诉我任何两个用户之间的步数差异。
示例:
user_names: dave and abha
steps difference: 3
说明: dave是pritesh的父母(1步)pritesh是拉里的父母(2步)拉里是abha的父母(3步)。
我已经尝试过以下查询:
SELECT (CASE
WHEN (count(T2.user_id) - 1) = -1
THEN 0
ELSE (count(T2.user_id) - 1)
END) as steps
FROM
(
SELECT
@r AS _id,
(
SELECT
@r := parent_user_id
FROM
USER
WHERE
user_id = _id
) AS parent_user_id,
@l := @l + 1 AS lvl
FROM
(
SELECT
@r := (select MAX(user_id) from USER),
@l := (select MIN(user_id) from USER)
) vars,
USER h
WHERE
@r <> 0
) T1
JOIN
USER T2
ON
T1._id = T2.user_id
WHERE
(CASE
WHEN (SELECT user_id FROM USER WHERE user_name= _name1) < (SELECT user_id FROM USER WHERE user_name= _name2)
THEN (T2.user_id BETWEEN (SELECT user_id FROM USER WHERE user_name= _name1) AND (SELECT user_id FROM USER WHERE user_name= _name2))
ELSE (T2.user_id BETWEEN (SELECT user_id FROM USER WHERE user_name= _name2) AND (SELECT user_id FROM USER WHERE user_name= _name1))
END)
ORDER BY
T1.lvl
DESC
答案 0 :(得分:4)
我找到了你的解决方案,可以找到2个节点之间的一些步骤。 我在您的查询中做了一些更改&amp;让它更容易。
select count(DISTINCT(parent_user_id)) -1 as Step_Difference
from (select * from USER
order by parent_user_id, user_id) products_sorted,
(select @pv := 0) initialisation
where find_in_set(parent_user_id, @pv)
and length(@pv := concat(@pv, ',', user_id))
AND
(CASE
WHEN (SELECT user_id FROM USER WHERE user_name= _name1) < (SELECT user_id FROM USER WHERE user_name= _name2) AND (SELECT COUNT(user_id) FROM USER WHERE(SELECT user_id FROM USER WHERE user_name = _name1) IN( SELECT parent_user_id FROM USER) ) > 0
THEN (user_id BETWEEN (SELECT user_id FROM USER WHERE user_name= _name1) AND (SELECT user_id FROM USER WHERE user_name= _name2))
WHEN (SELECT user_id FROM USER WHERE user_name= _name2) < (SELECT user_id FROM USER WHERE user_name= _name1) AND (SELECT COUNT(user_id) FROM USER WHERE(SELECT user_id FROM USER WHERE user_name = _name2) IN( SELECT parent_user_id FROM USER) ) > 0
THEN (user_id BETWEEN (SELECT user_id FROM USER WHERE user_name= _name2) AND (SELECT user_id FROM USER WHERE user_name= _name1))
ELSE (user_id = 1)
END)