How to select only years from mysql database (but only those years which contain data)?
SELECT DISTINCT(YEAR(datecolumn))
FROM mytable
I would like to categorize data by date (firstly, user selects year, then month, than day...). I'd also like to be able to use a similar approach for selection by months and/or days.
SELECT DISTINCT(MONTH(datecolumn))
FROM mytable
WHERE datecolumn >= CAST(CONCAT($year, '-01-01') AS DATETIME)
AND datecolumn < CAST(CONCAT($year + 1, '-01-01') AS DATETIME)
SELECT DISTINCT(DAY(datecolumn))
FROM mytable
WHERE datecolumn >= CAST(CONCAT_WS('-', $year, $month, '01') AS DATETIME)
AND datecolumn < CAST(CONCAT_WS('-', $year, $month, '01') AS DATETIME) + INTERVAL 1 MONTH
If you store what PHP
time()
returns in your columns, use this:
SELECT DISTINCT(YEAR(FROM_UNIXTIME(datecolumn)))
FROM mytable
SELECT DISTINCT(MONTH(FROM_UNIXTIME(datecolumn)))
FROM mytable
WHERE datecolumn >= CAST(CONCAT($year, '-01-01') AS DATETIME)
AND datecolumn < CAST(CONCAT($year + 1, '-01-01') AS DATETIME)
SELECT DISTINCT(DAY(FROM_UNIXTIME(datecolumn)))
FROM mytable
WHERE datecolumn >= UNIX_TIMESTAMP(CAST(CONCAT_WS('-', $year, $month, '01') AS DATETIME))
AND datecolumn < UNIX_TIMESTAMP(CAST(CONCAT_WS('-', $year, $month, '01') AS DATETIME) + INTERVAL 1 MONTH)
Note that the conditions we use here are sargable: datecolumn
is the only thing on one side of the expression, and an index can be used to search for it.