简体   繁体   中英

most effecient way to search SQL table using result from same table until final value is found

表

In the image above which represents an SQL table I would like to search 1111 and retrieve its last replaced number which should be 4444 where 1111 is just a single number replaced by a single number 4444. then i would like to search 5555 which should return (6666,9999,8888). NB 9999 had replaced 7777.

so 1111 was a single part number replaced multiple times and 5555 was a group number with multiple parts breakdown with one replaced number within(7777>>9999).

What would be the fastest and most efficient method?

  1. if possible a solution using SQL for efficiency.

  2. if unable within SQL then from within PHP.

What I have tried:

1) while loop. but need to access database 1000 times for 1000 replaced numbers. ##too inefficient.

2)

SELECT C.RPLPART 
FROM TABLE A 
  left join  TABLE B on A.RPLPART=B.PART# 
  left join TABLE C on B.RPLPART=C.PART#  
WHERE A.PART#='1111' ##Unable to know when last number is reached.

A recursive Common Table Expression (CTE) would seem to be the ticket.

Something like so...

with rcte (lvl, topPart, part#, rplpart) as 
  (select 1 as lvl, part#, part#, rplpart
   from MYTABLE
   union all
   select p.lvl + 1, p.topPart, c.part#, c.rplpart
   from rcte p, MYTABLE c
   where p.rplpart = c.part#
)
select topPart, rplpart 
from rcte
where toppart = 1111
order by lvl desc
fetch first row only;

You can do this using a recursive CTE that generates a complete replacement chain for a given starting part id, and then limit the result to just those that don't exist in the parts# column:

WITH cte(part) AS
  (SELECT replpart FROM parts WHERE part# = 1111
   UNION ALL
   SELECT parts.replpart FROM parts, cte WHERE parts.part# = cte.part)
SELECT DISTINCT part
FROM cte
WHERE part NOT IN (SELECT part# FROM parts);

Fiddle example

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM