简体   繁体   中英

optimizing a huge but simple mysql query of sums

how would one go about finding solutions to all possible combinations of a,b,c,d,e,f where

a+b+c+d+e+f = x

given a,b,c,d,e,f are integers between 0-999 and x is a fixed integer

and the solution

a,b,c,d,e,f < y

(where each comma is a thousand separator)

ex. the huge number 304,153,525,784,175,764 is a solution to x=2705

since: 304+153+525+784+175+764 = 2705

here's a query i am trying for x=2705 and y=304153525784175764

SELECT 
    a.id,
    b.id,
    c.id,
    d.id,
    e.id,
    f.id,
    a.id+b.id+c.id+d.id+e.id+f.id AS sum
    a.id*1000*1000*1000*1000*1000+
    b.id*1000*1000*1000*1000+
    c.id*1000*1000*1000+
    d.id*1000*1000+
    e.id*1000+
    f.id AS solution
FROM a JOIN b JOIN c JOIN d JOIN e JOIN f
WHERE sum = 2705
AND solution <= 304153525784175764
ORDER BY solution DESC

how can one simplify this query which is currently far too big

is there perhaps a simpler way to get the solutions?

If a=000, then the problem degenerates to finding b..f such that b+c+d+e+f =2705. There will be an awfully large number of solutions (with 3-digit values). My point is that the resultset is too big; so no query can be 'reasonably sized'.

Anyway, I would approach it from a programming language, then think about moving to SQL:

for a in (000..304)   -- this is the main use for "y"
    for b in (000..999)
        if a + b > 2705 then break
        for c in (000..999)
            if a + b + c > 2705 then break
            for d in (000..999)
                if a + b + c + d > 2705 then break
                for e in (max(000, 2705-1000-(a+b+c+d))..999)
                    if a + b + c + d + e > 2705 then break
                    f = 2705 - (a + b + c + d + e);
                    if f between 000 and 999 then
                        print a,b,c,d,e,f

(Perhaps I would handle 304 separately. Or maybe stop b at 153 only when a==304.)

I cringe to think how long this would take to run in a well-optimized compiler. And cringe even more at the size of the temp tables needed to do the task in SQL.

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