我有一个表“ table1 ”,其中有一个“ parents_list ”。现在,我将只获得每行状态最高的一个父级,并从该父级中获得下一个父级(2个或以上)。 我写的查询就是这个。但是它只返回“ parent_name&parent_name_2” NULL :
storageClassName: manual
表格:
SELECT t1.id, parents.name as parent_name, parents2.name as parent_name_2
from table1 as t1
LEFT JOIN table1 as parents ON parents.id = (
SELECT id from table1 WHERE parents_list IN (SUBSTR(REPLACE(t1.parents_list,';', ','),1 , CHAR_LENGTH(t1.parents_list) - 1)) AND status > 1 ORDER BY status DESC LIMIT 1
)
LEFT JOIN table1 as parents2 ON parents2.id = (
SELECT id from table1 WHERE parents_list IN (SUBSTR(REPLACE(parents2.parents_list,';', ','),2 , CHAR_LENGTH(parents2.parents_list) - 2)) AND status > 1 ORDER BY status DESC LIMIT 1
)
WHERE t1.date BETWEEN '2018-05-15' AND '2018-06-20'
“ ID:5”行的结果应为:
| id | name | date | parents_list | status |
| ---: | --- | --- | --- | ---: |
| 1 | test 1 | 2018-05-18 | | 3 |
| 2 | test 2 | 2018-05-25 | ;1; | 3 |
| 3 | test 3 | 2018-05-23 | ;5;1;4; | 8 |
| 4 | test 4 | 2018-05-30 | ;1;3; | 5 |
| 5 | test 5 | 2018-06-05 | ;2;4;3; | 6 |
但当前结果是:
| id | parent_name| parent_name_2 |
| 5 | test 3 | test 1 |
我如何才能使该查询生效,或者有更好的方法呢?
P.S。我无法更改表格设计:(