Optimize php mySQL query with mulitple joins and Group_Concat -
i have multiple join sets happening on query. have multiple joins, because of way tables structured want. main joins, i've separated 3 sets commented below. if have 1 set, query time pretty fast. when have 2 sets active, query time around 2 minutes. if 3 sets active shown below, takes long.
any on optimizing query appreciated.
$query = "select `databases`.*, `databasedescriptors`.*, `databasecontents`.*, `databaseaccesslevels`.*, `providers`.*, group_concat(`descriptors`.descriptorname separator ', ') descriptornames, group_concat(`contents`.contentname separator ', ') contentnames, group_concat(`accesslevels`.accesslevelname separator ', ') accesslevelnames "; $query .= "from `databases` "; // set 1 $query .= "join `databasedescriptors` on `databasedescriptors`.databaseid = `databases`.databaseid "; $query .= "join `descriptors` on `descriptors`.descriptorid = `databasedescriptors`.descriptorid "; //set 2 $query .= "join `databasecontents` on `databasecontents`.databaseid = `databases`.databaseid "; $query .= "join `contents` on `contents`.contentid = `databasecontents`.contentid "; //set 3 $query .= "join `databaseaccesslevels` on `databaseaccesslevels`.databaseid = `databases`.databaseid "; $query .= "join `accesslevels` on `accesslevels`.accesslevelid = `databaseaccesslevels`.accesslevelid "; $query .= "join `providers` on `providers`.providerid = `databases`.providerid "; $query .= "and `databases`.databaseid = 47";
the reason performance problem "database" has multiple descriptors, access levels, , contents. database has 10 of each. query ends turning 10*10*10 = 1000 rows processing.
the solution aggregation before doing join. instance, instead of this: $query .= "join databasedescriptors
on databasedescriptors
.databaseid = databases
.databaseid ";
$query .= "join `descriptors` on `descriptors`.descriptorid = `databasedescriptors`.descriptorid ";
you have:
(select dd.databaseid, group_concat(d.descriptorname separator ', ') descriptornames databasedescriptors dd join descriptions d on dd.descriptorid = d.descriptorid group dd.databaseid ) dd on databases.databaseid = dd.databaseid
(you can replace group dd.databaseid
where dd.databaseid = 47
handle 1 case. guess might want information databases. if so, add group databaseid
outer query.)
you need repeat 3 of group_concat()
columns.
note: pulling fields tables. however, 1 row returning because have aggregation query no group by
. i'm guessing getting duplicates in group_concat()
-created lists. approach fix problem.
Comments
Post a Comment