조회 : 644
1.
SELECT regday, SUM(cnt) cnt FROM (
SELECT regday, COUNT(*) cnt FROM `TBL1`
WHERE regday BETWEEN '2023-02-20' AND '2023-04-20'
GROUP BY regday
UNION ALL
SELECT regday, COUNT(*) cnt FROM `TBL2`
WHERE regday BETWEEN '2023-02-20' AND '2023-04-20'
GROUP BY regday
) A
GROUP BY regday
regday 가 등록일(Y-m-d)임
SELECT regday, COUNT(*) cnt FROM `TBL1`
WHERE regday BETWEEN '2023-02-20' AND '2023-04-20'
GROUP BY regday
여기서 group by 했는데.. 하지 말까?
어쨌든 union all 할꺼니깐.. row 로 뽑고 밖에서 count(*) 하면 될 것 같기고 하고...
2.
SELECT regday, COUNT(*) cnt FROM (
SELECT regday FROM `TBL1`
WHERE regday BETWEEN '2023-02-20' AND '2023-04-20'
UNION ALL
SELECT regday FROM `TBL2`
WHERE regday BETWEEN '2023-02-20' AND '2023-04-20'
) A
GROUP BY regday
위선 1번 쿼리는
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
------ ----------- ------------------- ---------- ------ ------------- ------ ------- ------ ------ -------- ----------------------------------------------
1 PRIMARY <derived2> (NULL) ALL (NULL) (NULL) (NULL) (NULL) 10468 100.00 Using temporary; Using filesort
2 DERIVED TBL1 (NULL) range regday regday 4 (NULL) 10262 100.00 Using where; Using index
3 UNION TBL2 (NULL) ALL (NULL) (NULL) (NULL) (NULL) 1856 11.11 Using where; Using temporary; Using filesort
2번 쿼리는
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
------ ----------- ------------------- ---------- ------ ------------- ------ ------- ------ ------ -------- ---------------------------------
1 PRIMARY <derived2> (NULL) ALL (NULL) (NULL) (NULL) (NULL) 10468 100.00 Using temporary; Using filesort
2 DERIVED TBL1 (NULL) range regday regday 4 (NULL) 10262 100.00 Using where; Using index
3 UNION TBL2 (NULL) ALL (NULL) (NULL) (NULL) (NULL) 1856 11.11 Using where
속도는
1. 0.025 sec
2. 0.050 sec
두배 차이나네.
메모리 사용량 등을 체크해야겠지만...뭐뭐뭐
1번이 3번동작에서
Using where; Using temporary; Using filesort
처럼 뒤에 두개가 더 붙음.
워, 이건 index 설저 안해서 생긴건데.. 뭐뭐뭐...
우선 1번으로 사용할 것이고
1번으로 하는 이유가 시작에 가까운 테이블(서브쿼리 결과) row 수가 적어야 쿼리가 더 효과적이 되기 때문임.
TBL2에 regday 에 index 태우는 것도 생각해볼까.. 2천건도 안되는데 불필요할려나?