How to create mysql table with column timestamp default current_date? - mysql

I need to create mysql table with default value on column CURRENT_DATE()
I try
DROP TABLE IF EXISTS `visitors`;
CREATE TABLE `visitors` (
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`ip` VARCHAR(32) NOT NULL,
`browser` VARCHAR(500) NOT NULL,
`version` VARCHAR(500) NOT NULL,
`platform` ENUM('w','l','m') NOT NULL,
`date` TIMESTAMP NOT NULL DEFAULT CURRENT_DATE(),
PRIMARY KEY (`id`),
UNIQUE KEY `person` (`ip`,`date`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
but it is writting an error
Query: CREATE TABLE `visitors` ( `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, `ip` VARCHAR(32) NOT NULL, `browser` VARCHAR(500) NO...
Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CURRENT_DATE() NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `person` (`ip`,`date`)
) ENGINE=INNODB AUTO_INCREMENT=1' at line 7
Execution Time : 0 sec
Transfer Time : 0 sec
Total Time : 0.063 sec
what is the problem?
I need to uniques only date
not with full time info...
can you help me?

Use CURRENT_TIMESTAMP function instead of CURRENT_DATE() function
Try this:
DROP TABLE IF EXISTS `visitors`;
CREATE TABLE `visitors` (
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`ip` VARCHAR(32) NOT NULL,
`browser` VARCHAR(500) NOT NULL,
`version` VARCHAR(500) NOT NULL,
`platform` ENUM('w','l','m') NOT NULL,
`date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `person` (`ip`,`date`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

you just have to replace CURRENT_DATE() by NOW() in your query.
I tried it and it's look ok.

This may be a little late but I think it might be helpful to someone else.
My approach has been to use getdate() like this:
[TimeStamp] [datetime] NOT NULL CONSTRAINT [DF_myTable_TimeStamp] DEFAULT (getdate()).
Where [TimeStamp] is the column in question.
The result is for example: 2017-11-02 11:58:34.203
To trim this, I use the following
declare #mydate datetime
set #mydate = '2017-11-02 11:58:34.203'
SELECT try_convert(nvarchar(20), #mydate, 120)
This final result is: 2017-11-02 11:58:34
You can actually set this in MSSQL Management Studio

Related

Optimise a MySQL query

I am using MySQL 8.0.20 and I have a huge table with some data in it.
CREATE TABLE `db_table` (
`utcDateTime` datetime DEFAULT NULL,
`dateTime` datetime DEFAULT NULL,
`col1` varchar(250) DEFAULT NULL,
`col2` varchar(10) DEFAULT NULL,
`col3` varchar(5) NOT NULL DEFAULT '1',
`col4` varchar(5) NOT NULL DEFAULT '1',
`id` int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
UNIQUE KEY `idx_dateIns` (`utcDateTime`,`col2`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8'
Below is the query I am trying to optimise,
SELECT col3,col4
from db_table
WHERE col2='123456'
AND (dateTime BETWEEN '2020-11-25 00:01' AND '2020-11-26 00:00')
group by utcDateTime
order by utcDateTime asc limit 1;
This query takes about 12 seconds to execute. But if I change the sorting order to desc, it takes about 0.015 seconds.
Can someone please help optimise the query or the database table?
Thank you

Mysql - Cannot add foreign key constraint, there is no forign key in SQL query

This question is completely different from similar ones. There is no foreign key in the SQL query. This is a silly error I see when I import the SQL file on remote server. This is the SQL code
CREATE TABLE `locations` (
`id` int(10) UNSIGNED NOT NULL,
`title` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
As you see there is no foreign key, But when I run the following code, it is ok
CREATE TABLE `locations` (
`id` int(10) UNSIGNED NOT NULL,
`title` varchar(191) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ;
If I rename it to something else it is OK too.
CREATE TABLE `locationssss` (
`id` int(10) UNSIGNED NOT NULL,
`title` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
what is wrong?
Just for future references:
Do you have more tables within your database? If so, is there a table that does contain a foreign key connected with the locations table?

what is my syntax error here in mySQL query?

CREATE TABLE IF NOT EXISTS `creditors` (
`id` int(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(50) NOT NULL,
`route` varchar(255) NOT NULL,
`mobile` int(10) NOT NULL,
`credit_amount` double(100) NOT NULL,
`start_date` date NOT NULL,
`due_date` date NOT NULL,
UNIQUE KEY `idUnique` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1
MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near ') NOT NULL,
start_date date NOT NULL,
due_date date NOT NULL, ' at line 6
What is my syntax error in this SQL query?
If you set a Column to primary key, it consists only Unique value. Then why did you try to made the same to UNIQUE KEY?
And also Delete the RANGE for Double.
SQLFiddle Example
CREATE TABLE `creditors` (
`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(50) NOT NULL,
`route` varchar(255) NOT NULL,
`mobile` int NOT NULL,
`credit_amount` double NOT NULL,
`start_date` date NOT NULL,
`due_date` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
The error is with this statement:
`credit_amount` double(100) NOT NULL
Give precision after 100 in double data type.
Solution:
`credit_amount` double(100,0) NOT NULL
Instead of 0 after 100 give number of digits after decimal point.
If you want to use double you must specify both M and D where
M is number digits in total, of which D digits may be after the decimal point, i.e. double(10,0). Otherwise use float which which allows syntax like float(10).
Also, unless you really benefit from this, do not use latin1 charset, but rather UTF-8

MySQL query error #1064?

I'm trying to import my old database but this gave me some errors what makes it impossible im also searching on google for 30 minuts and i can't find any solution?
SQL-query:
CREATE TABLE `UG_blogs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`catid` int(11) NOT NULL,
`ownerid` int(11) NOT NULL,
`content` text NOT NULL,
`date` datetime NOT NULL DEFAULT TIMESTAMP,
PRIMARY KEY (`id`), KEY id(`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
MySQL meldt: Documentatie
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '
PRIMARY KEY (`id`), KEY id(`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT C' at line 6
The correct default value is CURRENT_TIMESTAMP:
CREATE TABLE `UG_blogs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`catid` int(11) NOT NULL,
`ownerid` int(11) NOT NULL,
`content` text NOT NULL,
`date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY id(`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
The SQL Fiddle is here.
EDIT:
You must be using an old-ish version of MySQL (okay, not that old, just pre-5.6). Well, you can't default a datetime value (without a trigger), so you have to live with a TIMESTAMP value and learn to love the timestamp functions:
CREATE TABLE `UG_blogs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`catid` int(11) NOT NULL,
`ownerid` int(11) NOT NULL,
`content` text NOT NULL,
`date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY id(`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
First solution : change datatype into timestamp like this
CREATE TABLE `UG_blogs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`catid` int(11) NOT NULL,
`ownerid` int(11) NOT NULL,
`content` text NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY id(`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
The problem is : The Timestamp data type has a range of 1970-01-01 00:00:01 UTC to 2038-01-19 03:14:07.
So the second solution is, don't change datetime datatype into timestamp. But you need a trigger to set default value.

MySql - Create view to read from Multiple Tables

I have archived some old line items for invoices that are no longer current but still need to reference them. I think I need to create a VIEW but not really understanding it. Can someone help so I can run a query to pull the invoice and then the total of all the line items assigned (no matter what table the items are in)?
CREATE TABLE `Invoice` (
`Invoice_ID` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`Invoice_CreatedDateTime` DATETIME DEFAULT NULL,
`Invoice_Status` ENUM('Paid','Sent','Unsent','Hold') DEFAULT NULL,
`LastUpdatedAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`),
KEY `LastUpdatedAt` (`LastUpdatedAt`)
) ENGINE=MYISAM DEFAULT CHARSET=latin1
CREATE TABLE `Invoice_LineItem` (
`LineItem_ID` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`LineItem_ChargeType` VARCHAR(64) NOT NULL DEFAULT '',
`LineItem_InvoiceID` INT(11) UNSIGNED DEFAULT NULL,
`LineItem_Amount` DECIMAL(11,4) DEFAULT NULL,
`LastUpdatedAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`LineItem_ID`),
KEY `LastUpdatedAt` (`LastUpdatedAt`),
KEY `LineItem_InvoiceID` (`LineItem_InvoiceID`)
) ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1
CREATE TABLE `Invoice_LineItem_Archived` (
`LineItem_ID` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`LineItem_ChargeType` VARCHAR(64) NOT NULL DEFAULT '',
`LineItem_InvoiceID` INT(11) UNSIGNED DEFAULT NULL,
`LineItem_Amount` DECIMAL(11,4) DEFAULT NULL,
`LastUpdatedAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`LineItem_ID`),
KEY `LastUpdatedAt` (`LastUpdatedAt`),
KEY `LineItem_InvoiceID` (`LineItem_InvoiceID`)
) ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1
Typically I would just run the following query to get the amount due on the invoices
SELECT
Invoice_ID,
Invoice_CreatedDateTime,
Invoice_Status,
(SELECT SUM(LineItem_Amount) AS totAmt FROM Invoice_LineItem WHERE LineItem_InvoiceID=Invoice_ID) AS Invoice_Total
FROM
Invoice
WHERE
Invoice_Status='Sent'
Also how can I select all the line items from both tables in one query?
SELECT
LineItem_ID,
LineItem_ChargeType,
LineItem_Amount
FROM
Invoice_LineItem
WHERE
LineItem_InvoiceID='1234'
You can use the MERGE Storage Engine to create a virtual table that's the union of two real tables:
CREATE TABLE Invoice_LineItem_All
(
`LineItem_ID` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`LineItem_ChargeType` VARCHAR(64) NOT NULL DEFAULT '',
`LineItem_InvoiceID` INT(11) UNSIGNED DEFAULT NULL,
`LineItem_Amount` DECIMAL(11,4) DEFAULT NULL,
`LastUpdatedAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY (`LineItem_ID`),
KEY `LastUpdatedAt` (`LastUpdatedAt`),
KEY `LineItem_InvoiceID` (`LineItem_InvoiceID`)
) ENGINE=MERGE UNION=(Invoice_LineItem_Archived, Invoice_LineItem);
You can use UNION :
SELECT a.* FROM a
UNION
SELECT b.* FROM b;
You just need to have the same number and type of column in your different queries.
As far as I remember, you can add test in sub-queries, but I'm not sure you can order on the global result.
http://dev.mysql.com/doc/refman/4.1/en/union.html