V
V
vetsmen2017-09-13 13:28:33
MySQL
vetsmen, 2017-09-13 13:28:33

How to merge 2 sql into 1?

How to combine 2 SQL queries into one?
1) SELECT Cases.*, count(BotItems.id) AS "allcount" FROM Cases LEFT JOIN Items ON Items.caseid = Cases.id LEFT JOIN BotItems ON BotItems.itemid = Items.itemid GROUP BY Cases.id
2) SELECT Cases .*, count(BotItems.id) AS "typecount" FROM Cases LEFT JOIN Items ON Items.caseid = Cases.id AND Items.type = 1 LEFT JOIN BotItems ON BotItems.itemid = Items.itemid GROUP BY Cases.id
In the first In the query, I count the number of records in a certain table.
In the second query, I do the same, but add the "type" criterion, according to which the selection of records is limited
. As a result, I need to get both variables with the number of records, how to do this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Holub, 2017-09-13
@vetsmen

SELECT Cases.id, count(BotItems.id) AS "allcount", 
sum(case when (BotItems.itemid = Items.itemid and IFNULL(Items.type, 0) = 1) then 1 else 0 end) as "typecount"
FROM Cases LEFT JOIN Items ON Items.caseid = Cases.id 
LEFT JOIN BotItems ON BotItems.itemid = Items.itemid GROUP BY Cases.id

V
VisualIdeas, 2017-09-13
@VisualIdeas

SELECT Cases.*, count(BotItems.id) AS "alltypecount" FROM Cases LEFT JOIN Items ON Items.caseid = Cases.id LEFT JOIN BotItems ON BotItems.itemid = Items.itemid GROUP BY Cases.id
UNION
SELECT Cases.*, count(BotItems.id) AS "alltypecount" FROM Cases LEFT JOIN Items ON Items.caseid = Cases.id LEFT JOIN BotItems ON BotItems.itemid = Items.itemid AND Items.type = 1 GROUP BY Cases.id
The result will be 2 rows returned in column named alltypecount:
1) total
2) total by type

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question