Skip to content
Advertisement

MySQL – Join tables to a custom list/array of values

I would like to know if it’s possible to join tables into a custom set of values in MySQL. For example, I have a set of dates (outside the database). I would like to get the matched joins in a single query so that I can easily loop through the result. Like:

Data outside database

Date
2021-04-08
2021-04-09
2021-04-10
2021-04-11
2021-04-12

The Database may look like

Table: transactions

id date amount
1 2021-04-08 500
2 2021-04-08 600
3 2021-04-10 350

I want the result to be like:

Date Sum
2021-04-08 1100
2021-04-09 0
2021-04-10 350
2021-04-11 0
2021-04-12 0

In other words, I want to do:

Advertisement

Answer

Example:

id | date       | amount
-: | :--------- | -----:
 1 | 2021-04-08 |    500
 2 | 2021-04-08 |    600
 3 | 2021-04-10 |    350
date       |  sum
:--------- | ---:
2021-04-08 | 1100
2021-04-09 |    0
2021-04-10 |  350
2021-04-11 |    0
2021-04-12 |    0
date       |  sum
:--------- | ---:
2021-04-08 | 1100
2021-04-09 |    0
2021-04-10 |  350
2021-04-11 |    0
2021-04-12 |    0

db<>fiddle here

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement