Mysql unable to select datetime column - mysql

I'm trying to SELECT rows that matches datetime in my column. I have a table containing mDTS set as DATETIME (with no curly braces).
My table looks something like this:
mID
mDTS
mDTE
1
10/08/2021 10:41:47
11/08/2021 10:41:47
2
12/08/2021 10:42:34
13/08/2021 10:42:34
CREATE TABLE tb_cyc (
mID int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'ID cycle',
mDTS datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'Data inizio ciclo',
mDTE datetime DEFAULT '0000-00-00 00:00:00' COMMENT 'Data fine ciclo',
PRIMARY KEY (mID)
)
I'm trying to run the following query but it returns an empty set.
SELECT * FROM tb_cyc WHERE mDTS = '12/08/2021 10:42:34'
I've also tried:
SELECT * FROM tb_cyc WHERE mDTS LIKE '12/08/2021 10:42:34'
and
SELECT * FROM tb_cyc WHERE mDTS = '12/08/2021 %'
But none of this seems to work.
What am I doing wrong?

Change the format of the date in WHERE clause:
WHERE mDTS = '2021-08-12 10:42:34'
What happens is that mDTS is a datetime; when compared with a string MySQL will treat the string as a date/time. The literal value 12/08/2021 10:42:34 will generate the following warning:
Incorrect datetime value: '12/08/2021 10:42:34' for column 'mDTS' at row 1

Related

Update lot of data, date ( +1hour ), contraints uniq

I try to add 1hours for each value after specific date...
I have table like this :
Colonne Type
id int(11)
date datetime
value double
kind varchar(190)
data_id int(11) NULL
I have uniq constraints on 'date' . 'kind' . 'data_id'
I try :
update data set `date` = ADDTIME(`date`, '01:00:00') WHERE `date` > '2019-03-31 02:00:00';
But i get Error
Duplicate entry '2019-03-31 04:05:00-ManualDataValue-1' for key 'UNIQ_DATE_KIND_DATA_ID
I understand the error, the value exists, but I need to "move" all data ...
So if the request is performed in one block and the unique constraints is checked at the end, technically there is no error ...
How to perform this ?
( PS: SELECT * FROM data WHERE date > '2019-03-31 02:00:00' return 1,198,778 entry, so i can't do this manualy :/ )
Try:
update data set `date` = ADDTIME(`date`, '01:00:00') WHERE `date` > '2019-03-31 02:00:00' ORDER By date DESC
See this SO for more explanations.

Bulk apply alias to table columns in MYSQL

I'm working with a 3rd party MYSQL database over which I have no control except I can read from it. It contains 51 tables with identical column structure but slightly different names. They hold daily summaries for a different data source. Example Table:
CREATE TABLE `archive_day_?????` (
`dateTime` int(11) NOT NULL,
`min` double DEFAULT NULL,
`mintime` int(11) DEFAULT NULL,
`max` double DEFAULT NULL,
`maxtime` int(11) DEFAULT NULL,
`sum` double DEFAULT NULL,
`count` int(11) DEFAULT NULL,
`wsum` double DEFAULT NULL,
`sumtime` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
where ????? changes to indicate the type of data held.
The dateTime field is mirrored across all tables being midnight of every day since the system has been running.
I want to produce a single data set across all tables using an inner join on the dateTime. But to avoid writing
SELECT ad1.maxtime as ad1_maxtime, ad2.maxtime as ad2_maxtime...
51 times for 9 fields is there a way I can bulk create aliases e.g
ad1.* as ad_*, ad2.* as ad_* and so on.
I have looked at Create Aliases In Bulk? but this doesn't seem to work for MySQL. Ultimatly the data is being used by a Django ORM.
EDIT: Unfortunately Union doesn't uniquely identify the fields or group them together e.g.
SELECT * FROM `archive_day_ET` UNION ALL SELECT * FROM `archive_day_inTemp`
results in:
To generate a string with all the field names from those tables, you could query information_schema.columns
For example:
SELECT
GROUP_CONCAT(CONCAT(TABLE_NAME,'.`',column_name,'` AS `',column_name,'_',replace(TABLE_NAME,'archive_day_',''),'`') SEPARATOR ',\r\n')
FROM information_schema.columns
WHERE TABLE_NAME like 'archive_day_%'
A test on db<>fiddle here
And to generate the JOIN's then you could use information_schema.tables
For example:
SELECT CONCAT('FROM (\r\n ',GROUP_CONCAT(CONCAT('SELECT `dateTime` FROM ',TABLE_NAME) SEPARATOR '\r\n UNION\r\n '),'\r\n) AS dt \r\nLEFT JOIN ',
GROUP_CONCAT(CONCAT(TABLE_NAME,' ON ',
TABLE_NAME,'.`dateTime` = dt.`dateTime`') SEPARATOR '\r\nLEFT JOIN ')) as SqlJoins
FROM information_schema.tables
WHERE TABLE_NAME like 'archive_day_%'
A test on db<>fiddle here
For the 2 example tables they would generate
archive_day_ET.`dateTime` AS `dateTime_ET`,
archive_day_ET.`min` AS `min_ET`,
archive_day_ET.`mintime` AS `mintime_ET`,
archive_day_ET.`max` AS `max_ET`,
archive_day_ET.`maxtime` AS `maxtime_ET`,
archive_day_ET.`sum` AS `sum_ET`,
archive_day_ET.`count` AS `count_ET`,
archive_day_ET.`wsum` AS `wsum_ET`,
archive_day_ET.`sumtime` AS `sumtime_ET`,
archive_day_inTemp.`dateTime` AS `dateTime_inTemp`,
archive_day_inTemp.`min` AS `min_inTemp`,
archive_day_inTemp.`mintime` AS `mintime_inTemp`,
archive_day_inTemp.`max` AS `max_inTemp`,
archive_day_inTemp.`maxtime` AS `maxtime_inTemp`,
archive_day_inTemp.`sum` AS `sum_inTemp`,
archive_day_inTemp.`count` AS `count_inTemp`,
archive_day_inTemp.`wsum` AS `wsum_inTemp`,
archive_day_inTemp.`sumtime` AS `sumtime_inTemp`
And
FROM (
SELECT `dateTime` FROM archive_day_ET
UNION
SELECT `dateTime` FROM archive_day_inTemp
) AS dt
LEFT JOIN archive_day_ET ON archive_day_ET.`dateTime` = dt.`dateTime`
LEFT JOIN archive_day_inTemp ON archive_day_inTemp.`dateTime` = dt.`dateTime`

Get full value from column char(1)

I have the following table for storing information about student attendance:
attendance
( id INT(11)
, type CHAR(1)
, for_date DATETIME
);
When inserting a new record, Present, 2017-11-26, MySQL stores P in type column.
So I'm trying to get full value Present in dashboard page with SELECT query but fails.
Is it possible to get full value without change datetype of column?
Here's what I did:
SELECT `id`, CONVERT(`type`, CHAR(10)) AS type, `for_date` FROM `attendance`;
You should store the full text eg:
attendance
( id INT(11)
, type CHAR(16)
, for_date DATETIME
);
so you obtain all text using select ...
otherwise you should decode the returning values eg. using case when
SELECT `id`, case when type = 'P' then 'Present' end as my_type, `for_date`
FROM `attendance`;

MySQL - get date column from a table

I have a MySQL db with a MappingTable which consists of two columns. First column is a date column and another is ID - Autoincrement int column. I created this table for mapping dates and the ID's. When I query the date column with dates to retrieve the ID, no rows are getting selected. Any reason?
I tried
date_format in the SELECT query
str_to_date while checking in the WHERE clause
Compared like current_date > "2016-07-12" AND current_date <= "2016-07-12"
IfI compare LIKE "2016-07-1%" I'm getting matching rows but if I select "2016-07-12%" though there are matching rows, it is giving 0 rows.
I defined my column as DATE only.
Anything I'm missing here?
CREATE TABLE `mapping_table` (
`Current_date` date DEFAULT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8;
My question is, I want to select something like this.
select id from mapping_table where current_date="2016-07-12";
I tried with all approaches as mentioned above, but no rows are not retrieving.
use back tick on columns and table names so it wont be read/parse as keyword.
select `id` from `mapping_table` where `current_date` = "2016-07-12";
In the sample you provided you should use a date_format
select id from mapping_table where current_date= DATE_FORMAT("2016-07-12",'%Y-%d-%m') ;
or use a range
select id from mapping_table where current_date
BETWEEN DATE_FORMAT("2016-07-12",'%Y-%d-%m')
and DATE_FORMAT("2016-07-10",'%Y-%d-%m')

Setting TIME field to NULL with Zend_Db

I came across what looks like an odd issue with either Zend_Db or PHP's PDO MySQL driver, that perhaps stems from my lack of knowledge of those two.
Let's assume I have a MySQL Table with a NULLable TIME field. If I run a query like this in MySQL client:
UPDATE mytable SET mytime = NULL WHERE id = 1;
Everything works as expected and mytime field will hold NULL as value after this query.
However, if I run the exact same query in PHP through the Zend_Db_Adapter, the mytime field is set to '0:0:0' after such query:
$db->getConnection()->exec('UPDATE mytable SET mytime = NULL WHERE id = 1');
How do I set that TIME field to NULL?
I'm using PHP5.3 with PDO MySQL driver, Zend Framework 1.11 and MySQL 5.1.
What you have should work, i.e.:
$db->getConnection()->exec('UPDATE mytable SET mytime = NULL WHERE id = 1');
That should work. I tested it.
Caveat
If the data type time is NOT NULL, then trying to set it to NULL will cause the value NULL to be defaulted to 00:00:00, which may be unexpected behaviour e.g.:
CREATE TABLE `test` (
`time` datetime NOT NULL
);
Trying to insert or update the time field above with NULL will cause the value 00:00:00 to be inserted.
This is similar for date, datetime, and a few other data types. e.g. Trying to set a data type datetime which is NOT NULL to NULL will default its value to 0000-00-00 00:00:00.
NOTE: Mysql will not throw an error when you try to set a NULL value to a NUT NULL data type, you can change this behaviour by setting MySQL's SQL_MODE to STRICT_ALL_TABLES: see this stackoverflow question.
The Fix
Change the field to allow NULL and it should be fine:
CREATE TABLE `test` (
`time` datetime DEFAULT NULL
);
Now the time field can be set to NULL.
use new Zend_Db_Expr('NULL') instead of NULL :
$zend_null = new Zend_Db_Expr('NULL');
$db->getConnection()->exec("UPDATE mytable SET mytime = $zend_null WHERE id = 1");