Search code examples
sqlexpressionengine

Merge 2 sql queries


I have 2 sql queries running separately, what I would like to do is merge the two so I can extract both sets of data within one query.

The queries are using the ExpressionEngine query module and are below, I would like to extract total and total_2 in one query:

Query 1:

 SELECT COUNT(exp_channel_data.entry_id) AS total
 FROM exp_channel_data 
 JOIN exp_channel_titles 
     ON exp_channel_titles.entry_id = exp_channel_data.entry_id
 WHERE field_id_207 != '' 
     AND status = 'open'
     AND exp_channel_data.channel_id = '18'
     AND author_id = "CURRENT_USER"

Query 2:

 SELECT COUNT(exp_channel_data.entry_id) AS total_2
 FROM exp_channel_data
 JOIN exp_channel_titles
    ON exp_channel_titles.entry_id = exp_channel_data.entry_id 
  WHERE status = 'open' 
    AND exp_channel_data.channel_id = '18'
    AND author_id = "CURRENT_USER"

Solution

  • SELECT 
        SUM(CASE WHEN field_id_207 != '' then 1 else 0 end) as total_1,
        COUNT(exp_channel_data.entry_id) AS total_2 
    FROM exp_channel_data 
    JOIN exp_channel_titles 
    ON exp_channel_titles.entry_id = exp_channel_data.entry_id 
    AND status = 'open' 
    AND exp_channel_data.channel_id = '18' 
    AND author_id = "CURRENT_USER"