My objective is to write a query that will return all the Categories with 3 flag fields, like this:
ID | En | Ru | Fr
The language flags must be ON or OFF according to if is any Lesson record associated with the category.
My current statement is this:
SELECT c.ID,
(CASE WHEN c.ID IN (SELECT c.ID FROM Lessons AS l WHERE l.Category_Id = c.ID AND l.Language_Id = 1) THEN 1 ELSE 0 END) AS En,
(CASE WHEN c.ID IN (SELECT c.ID FROM Lessons AS l WHERE l.Category_Id = c.ID AND l.Language_Id = 2) THEN 1 ELSE 0 END) AS Ru,
(CASE WHEN c.ID IN (SELECT c.ID FROM Lessons AS l WHERE l.Category_Id = c.ID AND l.Language_Id = 3) THEN 1 ELSE 0 END) AS Fr
FROM LessonCategories AS c
The problem is that this query is VERY slow, since the Lessons table has more than 60,000 records, and i’m running over it 3 times.
I’m looking for a way to make this query more efficient.
I had a thought to use grouping on join between Categories and lessons but i dont know exactly how and if it is even possible.
The pseudo-code for more fast query is:
SELECT c.[ID],
COUNT(l.Language_Id = 1) > 0 AS En
COUNT(l.Language_Id = 2) > 0 AS Ru
COUNT(l.Language_Id = 3) > 0 AS Fr
FROM CategoryTreeView AS c
INNER JOIN Lessons AS l ON l.Category_Id = c.ID
GROUP BY c.[ID]
It it possible to express this using valid t-sql?
Or is any better way to handle this kind of query?
P.S. If it helps, i don’t care to get one bitwise flag field instead of the 3 language fields.
Thanks.
Well you have just to combine your two queries 😉