How to store NULL values in datetime fields in MySQL?

后端 未结 8 499
再見小時候
再見小時候 2020-11-29 05:44

I have a \"bill_date\" field that I want to be blank (NULL) until it\'s been billed, at which point the date will be entered.

I see that MySQL does not like NULL val

相关标签:
8条回答
  • 2020-11-29 06:31

    This is a a sensible point.

    A null date is not a zero date. They may look the same, but they ain't. In mysql, a null date value is null. A zero date value is an empty string ('') and '0000-00-00 00:00:00'

    On a null date "... where mydate = ''" will fail.
    On an empty/zero date "... where mydate is null" will fail.

    But now let's get funky. In mysql dates, empty/zero date are strictly the same.

    by example

    select if(myDate is null, 'null', myDate) as mydate from myTable where  myDate = '';
    select if(myDate is null, 'null', myDate) as mydate from myTable where  myDate = '0000-00-00 00:00:00'
    

    will BOTH output: '0000-00-00 00:00:00'. if you update myDate with '' or '0000-00-00 00:00:00', both selects will still work the same.

    In php, the mysql null dates type will be respected with the standard mysql connector, and be real nulls ($var === null, is_null($var)). Empty dates will always be represented as '0000-00-00 00:00:00'.

    I strongly advise to use only null dates, OR only empty dates if you can. (some systems will use "virual" zero dates which are valid Gregorian dates, like 1970-01-01 (linux) or 0001-01-01 (oracle).

    empty dates are easier in php/mysql. You don't have the "where field is null" to handle. However, you have to "manually" transform the '0000-00-00 00:00:00' date in '' to display empty fields. (to store or search you don't have special case to handle for zero dates, which is nice).

    Null dates need better care. you have to be careful when you insert or update to NOT add quotes around null, else a zero date will be inserted instead of null, which causes your standard data havoc. In search forms, you will need to handle cases like "and mydate is not null", and so on.

    Null dates are usually more work. but they much MUCH MUCH faster than zero dates for queries.

    0 讨论(0)
  • 2020-11-29 06:33

    For what it is worth: I was experiencing a similar issue trying to update a MySQL table via Perl. The update would fail when an empty string value (translated from a null value from a read from another platform) was passed to the date column ('dtcol' in the code sample below). I was finally successful getting the data updated by using an IF statement embedded in my update statement:

        ...
        my $stmnt='update tbl set colA=?,dtcol=if(?="",null,?) where colC=?';
        my $status=$dbh->do($stmt,undef,$iref[1],$iref[2],$iref[2],$ref[0]);
        ...
    
    0 讨论(0)
提交回复
热议问题