I have this table names MyLevels.
id | level | ParentLevelId
---------------------
1 | basic | 1
2 | silver| 1
3 | gold | 2
4 | stone | 3
5 | wood | 2
on this table every level has a parent level. For example the "gold"
level parent id is 2. It's mean the parent level is "silver"
.
So I need a query to get the below in a html table: Parent level comes from ParentLevelId
.
level | parent level | distance From Basic
-------------------------------------------
basic | basic | 0
silver | basic | 1
gold | silver | 2
The distance from basic
reference to the number that each level is far from basic
level.
For example the wood
level id is 5 and 5 - 1 = 4
. which means the it's 4 level far from basic
level.
This is the only code I have:
$conn->prepare('SELECT id, level, ParentLevelId FROM MyLevels');
Any help appreciated.
Thanks
You can join the table with itself to get the name of the parent level from the parent ID. Join it again to get the ID of the basic
level, so you can subtract the ID from that.
SELECT m2.level, m1.level AS parentLevel, m2.id - m3.id AS distanceFromBasic
FROM MyLevels AS m1
JOIN MyLevels AS m2 ON m1.id = m2.parentLevelId
CROSS JOIN MyLevels AS m3
WHERE m3.level = 'basic'
SELECT
ml1.level,
(
SELECT
ml2.level
FROM
MyLevels AS ml2
WHERE
ml2.id = ml1.ParentLevelId
) AS parentLevel,
(
SELECT
ml1.id - ml2.id
FROM
MyLevels AS ml2
WHERE
ml2.level = 'basic'
) AS distanceFromBasic
FROM
MyLevels AS ml1;
Just keep in mind this only works if that column is the primary key or is unique and that column is being used as the parentID.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.