1

In this query I am using a UNION to simply combined the results of two nearly identical queries. The single difference is that tp.t_id in the WHERE clauses is different. I've renamed the table names here simply to highlight how both queries in the UNION are similar. (I do not think it is relevant what those tables are actually called).

I'd like to know if there is a way to factor out the redundancy in these queries if for nothing else for maintenance purposes.

Thanks!

SELECT SUM(s.count) AS total
FROM Table1 s 
JOIN Table2 p ON p.id=s.p_id 
JOIN Table3 tp ON tp.p_id=s.p_id 
JOIN Table4 t ON tp.p_id=s.p_id 
WHERE s.g_id=1 AND tp.t_id=1 AND s.type=1
UNION 
SELECT SUM(s.count) AS total
FROM Table1 s 
JOIN Table2 p ON p.id=s.p_id 
JOIN Table3 tp ON tp.p_id=s.p_id 
JOIN Table4 t ON tp.p_id=s.p_id 
WHERE s.g_id=1 AND tp.t_id=2 AND s.type=1
4

1 回答 1

5

Yes, use IN():

SELECT SUM(s.count) AS total
FROM Table1 s 
JOIN Table2 p ON p.id=s.p_id 
JOIN Table3 tp ON tp.p_id=s.p_id 
JOIN Table4 t ON tp.p_id=s.p_id 
WHERE s.g_id=1 AND tp.t_id IN (1, 2) AND s.type=1
GROUP BY tp.t_id
于 2012-09-08T19:53:01.983 回答