MYSQL UNION DISTINCT

前端 未结 3 1654
青春惊慌失措
青春惊慌失措 2020-12-13 14:18

I have two selects that I\'m currently running as a UNION successfully.

(SELECT a.user_id,
          a.updatecontents AS city,
          b.country
   FROM use         


        
相关标签:
3条回答
  • 2020-12-13 14:36

    No. You cannot specify which exact field you need to distinct with. It only works with the whole row.

    As of your problem - just make your query a subquery and in outer one GROUP BY user_id

    SELECT * FROM 
    (SELECT a.user_id,a.updatecontents as city,b.country
    FROM userprofiletemp AS a
    LEFT JOIN userattributes AS b ON a.user_id=b.user_id
    WHERE typeofupdate='city')
    
    UNION DISTINCT
    
    (SELECT a.user_id,c.city,c.country
    FROM userverify AS a
    LEFT JOIN userlogin AS b ON a.user_id=b.user_id
    LEFT JOIN userattributes AS c ON a.user_id=c.user_id
    WHERE b.active=1 AND a.verifycity=0) x
    GROUP BY user_id
    
    0 讨论(0)
  • 2020-12-13 14:43

    MySQL UNION produces distinct rows—however, all column values in the row need to be distinct. If you wish to limit the distinction to a single or a few columns, when other columns are not distinct, you can wrap the UNION in a sub-query and GROUP BY the sub-query by the columns you wish to be unique.

    Here I wrap the entire UNION in a sub-query, give it an alias, then GROUP BY the desired unique column:

    SELECT * FROM (
    
    SELECT a.user_id,a.updatecontents as city,b.country
    FROM userprofiletemp AS a
    LEFT JOIN userattributes AS b ON a.user_id=b.user_id
    WHERE typeofupdate='city'
    
    UNION
    
    SELECT a.user_id,c.city,c.country
    FROM userverify AS a
    LEFT JOIN userlogin AS b ON a.user_id=b.user_id
    LEFT JOIN userattributes AS c ON a.user_id=c.user_id
    WHERE b.active=1 AND a.verifycity=0
    
    ) aa GROUP BY user_id;
    

    If you have more than one column you'd like to include in the distinction, list them after the GROUP BY: such as GROUP BY user_id, city.


    SIDE NOTE: since, in this case, UNION does not provide the desired distinction, there is no benefit to simply using UNION, and apparently "UNION ALL is much faster than UNION", therefore you can use UNION ALL to speed up this query.

    0 讨论(0)
  • 2020-12-13 14:48
    (SELECT a.user_id,a.updatecontents as city,b.country
    FROM userprofiletemp AS a
    LEFT JOIN userattributes AS b ON a.user_id=b.user_id
    WHERE typeofupdate='city')
    
    UNION ALL
    
    (SELECT a.user_id,c.city,c.country
    FROM userverify AS a
    LEFT JOIN userlogin AS b ON a.user_id=b.user_id
    LEFT JOIN userattributes AS c ON a.user_id=c.user_id
    WHERE b.active=1 AND a.verifycity=0
      AND a.user_id NOT IN
          ( SELECT user_id
            FROM userprofiletemp 
            WHERE typeofupdate='city'
          ) 
    );
    
    0 讨论(0)
提交回复
热议问题