Union/Merge more than one query !

Discussion in 'PHP' started by coool, Aug 9, 2007.

  1. coool

    coool New Member

    Joined:
    Jul 12, 2007
    Messages:
    46
    Likes Received:
    0
    Trophy Points:
    0
    Hi

    How can I merge the result of few quries that had been unioned ?

    example:
    SELECT item1,item2,item3 FROM table111 WHERE item2='something' GROUP BY item1
    UNION
    SELECT item1,item2,item3 FROM table222 WHERE item2='something' GROUP BY item1
    UNION
    SELECT item1,item2,item3 FROM table333 WHERE item2='something' GROUP BY item1

    NOTE:
    table111, table222, and table333 has the same structure
    always i'm asking for same items to be selected here and for same group by and where statment
    the difference is with the table names
    each table has different records than the other table

    Is there any available code to do this ! any solution !

    do you any idea of how doing this, do you have any simple example ?
     
  2. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Create a view for the query and then use group by!
     
  3. coool

    coool New Member

    Joined:
    Jul 12, 2007
    Messages:
    46
    Likes Received:
    0
    Trophy Points:
    0
    I've got one solution but still have one more problem

    I'm getting the most biggest count from multible tables

    this is what i'm using:

    PHP:
    $fields "Status,Count(names)";
    $table1 "myTable1";
    $table2 "myTable2";
    $groupBy "Status";
     
    $sql "SELECT * FROM((SELECT * FROM (SELECT $fields FROM $table1 GROUP BY $groupBy)AS $table1) UNION
           (SELECT * FROM(SELECT 
    $fields FROM $table2 GROUP BY $groupBy)AS $table2))AS MainTable GROUP BY $groupBy";
    so if my first table gives:
    status1 = 40 items
    status2 = 60 items

    and if my second table gives:
    status1 = 250
    status2 = 20

    the result from the above code is:
    status1 = 250
    status2 = 60

    which is not what i'm looking for (it's just outputing the biggest numbers)

    i want is this answer:
    status1 = 290
    status2 = 80

    what do you think ? : (
     
  4. coool

    coool New Member

    Joined:
    Jul 12, 2007
    Messages:
    46
    Likes Received:
    0
    Trophy Points:
    0
    don't worry

    I've figured out the solution

    I just needed to used UNION ALL instead of UNION

    Thanks :)
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice