开发者

how can I delete date in this table?

I have table like this

create table tbl_1(
  year int,
  month int, 
 day int
)

insert into tbl_1 values(2009,  11, 30)
insert into tbl_1 values(2010,   3,  4)
insert into tbl_1 values(2011,   5, 13)
i开发者_如何学Pythonnsert into tbl_1 values(20011, 12, 24)

I want to delete date from 2009-11-30 until 2011-5-13, but I can't because all of columns are int and I can't use this query :

delete from tbl_1 
 where year >=2009 
   and year<=2011 
   and month >=11 
   and month <=5 
   and day >=30 
   and day <=13

..because: 1 < month < 12 and 1 < day < 30

I know that this is terrible mistake.

I have many table that use this way for save date , please help me I don't have time to delete and recreate all of them.


You could do it like this:

DELETE FROM tbl_1 
WHERE (year * 10000 + month * 100 + day) BETWEEN 20091130 AND 20110513

I haven't tested this. I would recommend testing it first on a test system before running it on your production data so that you don't accidentally delete the wrong data.


In MySQL and PostgreSQL:

DELETE
FROM    tbl_1
WHERE   (2009, 11, 30) <= (year, month, date)
        AND (year, month, date) <= (2011, 5, 13)

In PostgreSQL you can even do:

DELETE
FROM    tbl_1
WHERE   (year, month, date) BETWEEN (2009, 11, 30) AND (2011, 5, 13)


Just use some more boolean operators:

DELETE FROM tbl_1
WHERE (year = 2009 AND (month > 11 OR (month = 11 AND day >= 30)))
OR year = 2010
OR (year = 2011 AND (month < 5 OR (month = 5 AND day <= 13)))

Not pretty, but it works.

Edit:

parametrized:

DELETE FROM tbl_1
WHERE (year = %minYear% AND (month > %minMonth% OR (month = %minMonth% AND day >= %minDay%)))
OR (year > %minYear% AND year < %maxYear%)
OR (year = %maxYear% AND (month < %maxMonth% OR (month = %maxMonth% AND day <= %maxDay%)))


Convert the columns to date in your where clause then:

DELETE tbl_1
WHERE CONVERT(DATETIME, CONVERT(VARCHAR(4), year) + '-' + convert(VARCHAR(2), month) + '-' + CONVERT(VARCHAR(2), day)) BETWEEN '20091130' AND '20110513'


Easiest way to do this is to use DATE_FORMAT. Like so:

...
WHERE DATE_FORMAT( CONCAT(year,"-",month,"-",day), '%Y-%m-%d' ) > "2009-11-30"
AND DATE_FORMAT( CONCAT(year,"-",month,"-",day), '%Y-%m-%d' ) < "2011-05-13"

Hope this helps! :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜