i have sqlite database 3 tables. each of these tables have 2 columns: name , value such tables have same records (name) different values. how select records part of least sum of values spanning across these tables such record names unique?
names: steven, jamie, michael, jordan, gary
values
(in order of names)
table 1: 1, 2, 3, 4, 5
table 2: 2, 3, 1, 5, 6
table 3: 9, 0, 2, 11, 3
the output should return (steven, michael, jamie) because sum of values in case equal 2 least possible.
first, sql tables represent unordered sets. so, there no correspondence between 2 tables based on position. instead, let me assume each has name column.
second, sql doesn't optimization, need in brute force way. is, generate combinations , choose minimum value.
that uses cross join:
select min(t1.value + t2.value + t3.value) table1 t1 cross join table2 t2 cross join table3 t3 t1.name <> t2.name , t3.name not in (t1.name, t2.name); or, if want names:
select (t1.value + t2.value + t3.value), t1.name, t2.name, t3.name table1 t1 cross join table2 t2 cross join table3 t3 t1.name <> t2.name , t3.name not in (t1.name, t2.name) order (t1.value + t2.value + t3.value) limit 1
Comments
Post a Comment