How do I Combine these SQL SELECT queries into one SELECT statement

前端 未结 5 1750
挽巷
挽巷 2021-01-17 22:17

How do I combine these two select statements into one query:

SELECT SUM( incidents )  AS fires, neighborhoods AS fire_neighborhoods
FROM (
SELECT * 
FROM `fi         


        
5条回答
  •  后悔当初
    2021-01-17 23:04

    The answers given by the others of using a discriminator column look like what you are after, but just in case, it is possible to add dummy place holder columns to unions as shown below:

    SELECT 
        SUM( incidents )  AS fires, 
        neighborhoods AS fire_neighborhoods,
        0 as adw,
        '' as adw_neighbourhoods
    FROM ( 
        SELECT *  
        FROM `fires_2009_incident_location`  
        UNION ALL SELECT *  
        FROM `fires_2008_incident_location` 
        UNION ALL SELECT *  
        FROM `fires_2007_incident_location` 
        UNION ALL SELECT *  
        FROM `fires_2006_incident_location` 
    ) AS combo 
    GROUP BY fire_neighborhoods ORDER BY fires DESC 
    
    UNION 
    
    SELECT 
        0 as fires,
       '' as fire_neighbourhoods,
        SUM( incidents )  AS adw, 
        neighborhoods AS adw_neighborhoods 
    FROM ( 
        SELECT *  
        FROM `adw_2009_incident_location`  
        UNION ALL SELECT *  
        FROM `adw_2008_incident_location` 
        UNION ALL SELECT *  
        FROM `adw_2007_incident_location` 
        UNION ALL SELECT *  
        FROM `adw_2006_incident_location` 
    ) AS combo2 
    GROUP BY adw_neighborhoods ORDER BY adw DESC
    

提交回复
热议问题