Question

I have problem with my MySQL query.

I would like to query for delete rows oldest by 7 day from my table. This table has day, month and year in different rows.

This is my query:

DELETE FROM 
  `logowanie_dj` 
WHERE 
  `miesiac` 
IN (
  SELECT CONCAT(dzien,':', miesiac,':', rok) < 21:1:2014'
)

However mysql_query() is deleting all the rows.

Was it helpful?

Solution

I presume that you mean year, month and day are in different columns?

Then this might work:

DELETE FROM `logowanie_dj` WHERE CAST(CONCAT(dzien,':',miesiac,':',rok) AS DATE) < CAST('21:1:2014' AS DATE)

It creates a date value in the form dd:mm:yyyy from the cells of the row and deletes it if it is before 21:1:2014.

Please note that you obviously use some date format that is non-english. MySQL might have a problem with that, so that it could be you need to do this:

DELETE FROM `logowanie_dj` WHERE CAST(CONCAT(rok,'-',miesiac,'-',dzien) AS DATE) < CAST('2014-01-21' AS DATE)

OTHER TIPS

check the date and time format is correct or not. Try with this format 'yyyy:mm:dd hh:mm:ss'

You may want to try casting the two strings into dates so it knows to do the comparison as dates.

"For best results when using BETWEEN with date or time values, use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE."

Source

* Backup your database before trying this *

DELETE FROM `logowanie_dj` 
WHERE ABS(UNIX_TIMESTAMP()-UNIX_TIMESTAMP(CONCAT(rok,'-',miesiac,'-',dzien))) > 604800

Try with below code

    DELETE FROM 
  `logowanie_dj` 
WHERE 
  `miesiac` 
IN (
  SELECT CONCAT(dzien,':', miesiac,':', rok) < '2014:01:21 00:00:00'
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top