Prevent MySQL from duplicates per given project - mysql

I have this MySQL table
CREATE TABLE `d_hits` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`projectId` varchar(36) NOT NULL,
`data` text CHARACTER SET utf8,
`extras` text,
`status` varchar(50) NOT NULL DEFAULT 'notDone',
`evaluation` varchar(50) DEFAULT 'NONE',
`isGoldenHIT` tinyint(1) DEFAULT '0',
`goldenHITResultId` int(11) unsigned DEFAULT '0',
`notes` text,
`created_timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`isURL` tinyint(4) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3561574 DEFAULT CHARSET=latin1;
My goal here is to prevent the database from creating duplicates data for a given project. For example, project with projectID: 123 has data: link1 but if I enter data: link1 again it should prevent it from entering. However if projectID is 333 and the given data is again link1, it should insert it without any problems. My question is, how can I prevent the duplicates per project?

You seem to want a unique constraint.
ALTER TABLE d_hits
ADD UNIQUE (projectid,
data);

Related

MySQL INSERT results in duplicate key, but no duplicate exists

I have read through many entries that people have claimed to have this problem and they've solved their issue but none of their answers solve MY issue. I am using phpMyAdmin to update the email address of a user. The "user_email" field is marked as UNIQUE. Whenever I update the email address to his actual email, I get:
Duplicate entry 'user#example.com' for key 'user_email'
I have Analyzed, Optimized, and Repaired the table and no errors appear -- everything comes up as OK.
I have run several SQL statements to find any duplication only to find out that none exists.
I even exported the table and imported the records again. I add the indexes and try and update... duplicate entry message. Here's the table structure:
CREATE TABLE IF NOT EXISTS `users` (
`id` bigint(20) NOT NULL,
`md5_id` varchar(200) NOT NULL DEFAULT '',
`full_name` tinytext,
`user_name` varchar(200) DEFAULT NULL,
`user_email` varchar(220) DEFAULT NULL,
`user_level` tinyint(4) NOT NULL DEFAULT '1',
`pwd` varchar(220) NOT NULL DEFAULT '',
`address` text COLLATE latin1_general_ci,
`country` varchar(200) DEFAULT NULL,
`tel` varchar(200) NOT NULL DEFAULT '',
`fax` varchar(200) DEFAULT NULL,
`website` text,
`date` date NOT NULL DEFAULT '0000-00-00',
`users_ip` varchar(200) NOT NULL DEFAULT '',
`approved` int(1) NOT NULL DEFAULT '0',
`activation_code` int(10) NOT NULL DEFAULT '0',
`banned` int(1) NOT NULL DEFAULT '0',
`ckey` varchar(220) NOT NULL DEFAULT '',
`ctime` varchar(220) NOT NULL DEFAULT '',
`location` tinyint(4) NOT NULL DEFAULT '9'
) ENGINE=MyISAM AUTO_INCREMENT=210 DEFAULT CHARSET=latin1;
ALTER TABLE `users` ADD PRIMARY KEY (`id`);
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=210;
Even now that I have REMOVED the UNIQUE index from the 'user_email' field, the error is STILL coming up. I REALLY don't understand that (Maybe something residual...? I'm just guessing).
Picture me with wads of hair in my hands. Can anyone please help?
UPDATE:
Here's the output from SHOW CREATE TABLE users
Here's the output from SHOW INDEX FROM users
Error message while editing:
Error message without using database name:
Output of: SHOW CREATE TABLE proctor.users

Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause

I always get the error:
Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause
DROP TABLE IF EXISTS `characters`;
CREATE TABLE `characters`(
`id` int(11) NOT NULL AUTO_INCREMENT,
`accId` int(11) NOT NULL,
`charId` int(11) NOT NULL,
`charType` int(11) NOT NULL,
`level` int(11) NOT NULL,
`exp` int(11) NOT NULL,
`fame` int(11) NOT NULL,
`items` varchar(128) NOT NULL,
`hp` int(11) NOT NULL,
`mp` int(11) NOT NULL,
`stats` varchar(64) NOT NULL DEFAULT '"1,2,3,4,5,6,7,8"',
`dead` tinyint(1) NOT NULL DEFAULT '0',
`tex1` int(11) NOT NULL DEFAULT '0',
`tex2` int(11) NOT NULL DEFAULT '0',
`pet` int(11) NOT NULL DEFAULT '0',
`fameStats` varchar(128) NOT NULL DEFAULT 'eNoVytkRgCAMRdGH4IIbgmsPdmNVNmZf5n7kzM0kksLjJN2V4b30vcHK1YYam9hCxxqh5zpQI0wwQ4IFMhRYYeNjpw444YIfA3kDIA',
`createTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`deathTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`totalFame` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;
This is my first time using MySQL stuff. The reason I am using it because I downloaded a source for a game with server and this is needed.
The problem is isolated to these two lines
`createTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`deathTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
To get rid of the error, you need to modify one of those lines to remove the DEFAULT CURRENT_TIMESTAMP. MySQL only allows one timestamp column to be defined that way. For example:
`createTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`deathTime` timestamp NOT NULL,
Because the deathTime column is defined as NOT NULL and doesn't have a default, you'll need to supply a value for deathTime whenever you insert a row. You could get the current date and time assigned to that column for an INSERT using a BEFORE INSERT trigger.
You are trying to, well, define more than "one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause". Specifically, createTime and deathTime.
You Can't Do That.™

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

Find row that have a duplicate field, the filed type is blob

I have a table with many many duplicated row, I cannot create a unique value for the blob field, because is too large.
How can I find and delete the duplicate rows where the blob field (answer) is duplicated?
This is the table structure :
CREATE TABLE `answers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_question` int(11) NOT NULL,
`id_user` int(11) NOT NULL,
`answer` blob NOT NULL,
`language` varchar(2) NOT NULL,
`datetime` datetime NOT NULL,
`enabled` int(11) NOT NULL DEFAULT '0',
`deleted` int(11) NOT NULL DEFAULT '0',
`spam` int(11) NOT NULL DEFAULT '0',
`correct` int(11) NOT NULL DEFAULT '0',
`notification_send` int(11) NOT NULL DEFAULT '0',
`correct_notification` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `id_question` (`id_question`),
KEY `id_user` (`id_user`),
KEY `enabled` (`enabled`)
) ENGINE=InnoDB AUTO_INCREMENT=1488 DEFAULT CHARSET=utf8mb4
probable you can use prefix of the column by substr() or left() and compare. How much size you want to take that depends on your data distribution or prefix uniqueness of the column data.
for uniqueness check you can fire the below query if the
select count(distinct left(answer, 128))/count(*), count(distinct left(answer, 256))/count(*) from answers.
This will provide you selectivity or data distribution in your column. suppose 128 gives you answer as 1 i.e. all unique if you take first 128 bytes then choose that amount of data from each row and work. Hope it helps.

Mysql Append table to add columns

I like to append a table to add column but without using alert table command
e.g.
This is the table which is missing some columns.
CREATE TABLE IF NOT EXISTS `admin` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(20) NOT NULL,
`passwd` varchar(40) NOT NULL,
`isActive` tinyint(1) NOT NULL default '1',
`lastVisit` datetime NOT NULL default '0000-00-00 00:00:00',
`modifyAt` datetime NOT NULL,
`createdAt` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
So if i run this query then it should automatically add missing columns into my tables
CREATE TABLE IF NOT EXISTS `admin` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(20) NOT NULL,
`passwd` varchar(40) NOT NULL,
`name` varchar(100) NOT NULL,
`originalUser` tinyint(1) NOT NULL default '0',
`isActive` tinyint(1) NOT NULL default '1',
`lastVisit` datetime NOT NULL default '0000-00-00 00:00:00',
`modifyAt` datetime NOT NULL,
`createdAt` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Can this be possible to do without using alert table command ?
I understand your question as you want to add some columns to your table. Please be informed that the term row is usually related to the actual data in your table, not the columns itself. If my assumption is wrong, please clarify your question.
You cannot use CREATE TABLE for altering a table. It is there to create table,
and if it cannot create it, it will in most cases throw an error like you described. Another command exists for that reason: ALTER TABLE.
You might do it something like this.
(1) Create your table with your CREATE TABLE syntax above:
CREATE TABLE IF NOT EXISTS `admin` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(20) NOT NULL,
`passwd` varchar(40) NOT NULL,
`isActive` tinyint(1) NOT NULL default '1',
`lastVisit` datetime NOT NULL default '0000-00-00 00:00:00',
`modifyAt` datetime NOT NULL,
`createdAt` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
(2) Use ALTER TABLE like this to make the modifications I think you want to have in your second statement (two more columns):
ALTER TABLE
ADD COLUMN `name` varchar(100) NOT NULL AFTER `passwd`,
ADD COLUMN `originalUser` tinyint(1) NOT NULL default '0' AFTER `name`;
Not related to your question, but I'd avoid column names like name, because if you don't escape them properly it'll throw you other errors (see reserved words).