Best Way to Combine Results from 2 mySQL Searches, into One Sorted List?
am 20.08.2007 23:32:46 von Vik Rubenfeld
I have to search 2 mySQL tables, and show the user a single sorted list
that contains all the results from both mySQL queries.
My question is, how do you get all the resulting items from both
databases into one single, sorted list, to present to the user?
I guess one way would be, to use PHP to copy all the results from each
database, into a PHP array, and then sort it. Is that how this kind of
thing is usually done?
Thanks in advance to all for any info.
Re: Best Way to Combine Results from 2 mySQL Searches, into One Sorted List?
am 20.08.2007 23:40:21 von luiheidsgoeroe
On Mon, 20 Aug 2007 23:32:46 +0200, Vik Rubenfeld =
wrote:
> I have to search 2 mySQL tables, and show the user a single sorted lis=
t
> that contains all the results from both mySQL queries.
I'm curious about the data/tables, it might be possible to do all this o=
n =
a MySQL level instead of PHP, which would usually be better.
> My question is, how do you get all the resulting items from both
> databases into one single, sorted list, to present to the user?
$list =3D array();
$r1 =3D mysql_query("Enter query one here");
while($row =3D mysql_fetch_assoc($r1)) $list[] =3D $row;
$r2 =3D mysql_query("Enter query two here");
while($row =3D mysql_fetch_assoc($r2)) $list[] =3D $row;
//untested....:
$fieldname =3D 'foo'; //<- enter the fieldname to sort by
usort($list, create_function('$a,b',"if(\$a['{$fieldname}'] == =
\$b['{$fieldname}']) return 0; return \$a['{$fieldname}'] > =
\$b['{$fieldname}'] ? 1 : -1;");
> I guess one way would be, to use PHP to copy all the results from each=
> database, into a PHP array, and then sort it. Is that how this kind of=
> thing is usually done?
The database software is optimised for this kind of stuff, so if it can =
be =
done there that would be highly preferable.
-- =
Rik Wasmus
Re: Best Way to Combine Results from 2 mySQL Searches, into One Sorted List?
am 21.08.2007 02:29:44 von zeldorblat
On Aug 20, 5:32 pm, Vik Rubenfeld wrote:
> I have to search 2 mySQL tables, and show the user a single sorted list
> that contains all the results from both mySQL queries.
>
> My question is, how do you get all the resulting items from both
> databases into one single, sorted list, to present to the user?
>
> I guess one way would be, to use PHP to copy all the results from each
> database, into a PHP array, and then sort it. Is that how this kind of
> thing is usually done?
>
> Thanks in advance to all for any info.
Use union: