by tosswin [SQL Query] mariadb 행으로 추가 [2023.10.17 11:37:37]
db를 사용하는 중에 아래와 같이 구현해야 하는 상황이 생겨 문의드립니다.
구성되어 있는 2개의 테이블이 있습니다.
table_a
rundatetime | item_A |
2023-01-01 00:00:00 | 56 |
2023-01-01 00:10:00 | 45 |
2023-01-01 00:20:00 | 55 |
table_b
rundatetime | idx_no | item_B |
2023-01-01 00:00:00 | 1 | 5 |
2023-01-01 00:00:00 | 2 | 49 |
2023-01-01 00:00:00 | 3 | 87 |
2023-01-01 00:10:00 | 1 | 4 |
2023-01-01 00:10:00 | 2 | 46 |
2023-01-01 00:10:00 | 3 | 89 |
2023-01-01 00:20:00 | 1 | 7 |
2023-01-01 00:20:00 | 2 | 45 |
2023-01-01 00:20:00 | 3 | 92 |
위 2개의 테이블을 아래 table_r 처럼 조회하고 싶습니다.
기준은 rundatetime입니다.
그리고 행으로 추가될 때 table_a에 대한 idx_no 는 0으로 변경하고 싶습니다.
runDatetime | idx_no | item |
2023-01-01 00:00:00 | 0 | 56 |
2023-01-01 00:00:00 | 1 | 5 |
2023-01-01 00:00:00 | 2 | 49 |
2023-01-01 00:00:00 | 3 | 87 |
2023-01-01 00:10:00 | 0 | 45 |
2023-01-01 00:10:00 | 1 | 4 |
2023-01-01 00:10:00 | 2 | 46 |
2023-01-01 00:10:00 | 3 | 89 |
2023-01-01 00:20:00 | 0 | 55 |
2023-01-01 00:20:00 | 1 | 7 |
2023-01-01 00:20:00 | 2 | 45 |
2023-01-01 00:20:00 | 3 | 92 |
table_r 처럼 조회하는 것도 가능할까요?
조언부탁드리겠습니다.
감사합니다.
with table_a ( rundatetime, item_a) as ( select '2023-01-01 00:00:00', 56 union all select '2023-01-01 00:10:00', 45 union all select '2023-01-01 00:20:00', 55 ), table_b ( rundatetime, idx_no, item_b) as ( select '2023-01-01 00:00:00', 1, 5 union all select '2023-01-01 00:00:00', 2, 49 union all select '2023-01-01 00:00:00', 3, 87 union all select '2023-01-01 00:10:00', 1, 4 union all select '2023-01-01 00:10:00', 2, 46 union all select '2023-01-01 00:10:00', 3, 89 union all select '2023-01-01 00:20:00', 1, 7 union all select '2023-01-01 00:20:00', 2, 45 union all select '2023-01-01 00:20:00', 3, 92 ) select rundatetime, idx_no, item from (select rundatetime, 0 idx_no, item_a item from table_a union all select rundatetime, idx_no, item_b from table_b ) table_r order by rundatetime, idx_no