www.webdeveloper.com
Results 1 to 7 of 7

Thread: [RESOLVED] UNION & GROUP BY (simple)

  1. #1
    Join Date
    May 2012
    Posts
    7

    resolved [RESOLVED] UNION & GROUP BY (simple)

    Hi, i have a problem with using union and group by together.
    the following:

    PHP Code:
    SELECT FROM `table1UNION SELECT FROM `table2WHERE metal '1' GROUP BY width 
    this returns in my dropdown:

    Code:
    2
    4
    5
    6
    2
    4
    5
    6
    the group by seems to work but only for one table at a time.
    i would like it to work with both tables so it should only display 2,4, 5,6.

    Any Ideas why its not working correctly?

    Regards
    David

  2. #2
    Join Date
    Jun 2007
    Posts
    400
    Does this work?

    Code:
    SELECT * FROM `table1` WHERE metal = '1' GROUP BY width UNION SELECT * FROM `table2` WHERE metal = '1' GROUP BY width

  3. #3
    Join Date
    May 2012
    Posts
    7
    Sorry, Sadly it still shows duplicate numbers still.

    Its like the code before and after UNION are handled like 2 seperate querys.

    Im pretty stuck with this.

  4. #4
    Join Date
    Jun 2007
    Posts
    400
    I think that's how a UNION works (as far as I know) it just executes multiple statements and then pieces them together. Generally UNION by default is supposed to return distinct results, but maybe try UNION DISTINCT?

  5. #5
    Join Date
    May 2012
    Posts
    17
    PHP Code:
    select FROM
    (
        
    SELECT FROM `table1
        
    UNION 
        SELECT 
    FROM `table2WHERE metal '1' 
    )
    GROUP BY width 

  6. #6
    Join Date
    May 2012
    Posts
    7
    Thanks Alan it had an error as it needs to be defined an alias, but you helped me with the overall design of the statement. Thanks Allot !!

    PHP Code:
    select FROM
    (
        
    SELECT FROM `table1WHERE metal '1' 
        
    UNION 
        SELECT 
    FROM `table2WHERE metal '1' 

    )AS randomname
    GROUP BY width 

  7. #7
    Join Date
    May 2012
    Posts
    17
    Whoops, sorry about that! Glad you got it sorted!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles