Re: Basic Dual Query Combine into one question

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi Dave and gang,

Just gonna chime in with a gotcha on the union query and that is that the
datatypes from the subsequent queries must match the datatypes returned by
the first query (at least for mysql).

Other than that, a simple query might be

select * from users where state in('california','texas') order by state,
last_name

which should result in the users grouped by state and ordered by last name
per state

hth,

Bastien

On Sat Jan 24 2015 at 7:36:11 AM Domain nikha.org <mail@xxxxxxxxx> wrote:

> Piers am Freitag, 23. Januar 2015 - 03:26:
> > On 23/01/15 11:50, dealTek wrote:
> > > Hi all, (newbie question)
> > >
> > > - let's say, (for some other reasons I'll skip here) I needed to do
> two separate queries to the same mysql contacts table (rather than one more
> elegant combined one)
> > >
> > > 1 - find everybody from California
> > > 2 - find everybody from Texas
> > >
> > > Then – I would like to combine both of these queries into some kind of
> an array that I could loop through and display after sorting by last name
> > >
> > > Q: I am curious the best way to combine the 2 separate queries into 1
> afterwards?
> > >
> > >
> > >
> >
> > Hi dealTek,
> >
> > If you are using MySQL you could look at the UNION clause. It allows you
> > to do two very different queries and combine them into one result set /
> > array.
> >
> > 1st hit I could find.
> >
> > http://www.w3schools.com/sql/sql_union.asp
> >
> > eg:
> >
> > SELECT City, State FROM contacts
> > WHERE State='California' AND cat_lover = 'Yes'
> > UNION ALL
> > SELECT City, State FROM contacts
> > WHERE State='Texas' AND has_hats = 'No'
> > ORDER BY City;
> >
> > Would that achieve the same result in one query?
> >
> > Cheers
> >
> >
> > P
> >
>
> Hi,
> Even more simple, try:
> SELECT City, State FROM contacts WHERE (State="California" OR
> State="Texas") ORDER BY lastname
>
> (you have something like a "lastname"-field in your contacts, I suppose)
>
>
> Cheers, Niklaus
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux