I have been successful in adding a new column to my table in MySQL. However I can't seem to add any data to it. I have tried using an UPDATE but I get an error. I am including the original code for the table, and the ALTER that added the column and the attempted update.
CREATE TABLE `Teams` (
`Team_id` INTEGER unsigned NULL AUTO_INCREMENT DEFAULT NULL,
`team name` VARCHAR(50) NULL DEFAULT NULL,
`league` CHAR(2) NULL DEFAULT NULL,
`div` VARCHAR(15) NULL DEFAULT NULL,
PRIMARY KEY (`Team_id`)
);
the filling (abbreviated)
INSERT INTO `Teams` (`team name`,`league`,`div`) VALUES
('Free Agent','',''),
('Blue Jays','AL','East'),
('Yankees','AL','East'),
('Orioles','AL','East'),
...and so on
The ALTER:
ALTER TABLE Teams
ADD City VARCHAR(20);
The UPDATE:
UPDATE Teams
SET City='NONE' where (team name='Free Agent');
You should escape identifiers if they contain spaces:
UPDATE `Teams`
SET `City`='NONE' where (`team name`='Free Agent');
Related
I'm stuck when creating my trigger in mysql (on phpmyadmin), and that's why I come to ask for your help
I have 2 tables : Assemblage and Bicyclette.
Tables Diagram:
Assemblage was built like this :
CREATE TABLE `Assemblage` (
`ID_Assemblage` int(11) NOT NULL AUTO_INCREMENT,
`Nom_Assemblage` varchar(255) NOT NULL,
`Grandeur_Assemblage` enum('Dames','Hommes','Garçons','Filles','Adultes','Jeunes') NOT NULL,
`Cadre_Assemblage` varchar(10) NOT NULL,
`Guidon_Assemblage` varchar(10) NOT NULL,
`Freins_Assemblage` varchar(10) DEFAULT NULL,
`Selle_Assemblage` varchar(10) NOT NULL,
`DerailleurAvant_Assemblage` varchar(10) DEFAULT NULL,
`DerailleurArriere_Assemblage` varchar(10) DEFAULT NULL,
`RoueAvant_Assemblage` varchar(10) NOT NULL,
`RoueArriere_Assemblage` varchar(10) NOT NULL,
`Reflecteurs_Assemblage` varchar(10) DEFAULT NULL,
`Pedalier_Assemblage` varchar(10) NOT NULL,
`Ordinateur_Assemblage` varchar(10) DEFAULT NULL,
`Panier_Assemblage` varchar(10) DEFAULT NULL,
PRIMARY KEY (`ID_Assemblage`)
)
And here Bicyclette :
CREATE TABLE `Bicyclette` (
`ID_Bicyclette` int(11) NOT NULL AUTO_INCREMENT,
`ID_Assemblage` int(11) NOT NULL,
`Prix_Bicyclette` float NOT NULL,
`Categorie_Bicyclette` enum('VTT','Vélo de course','Classique','BMX') NOT NULL,
`DateIntroduction_Bicyclette` date NOT NULL,
`DateFin_Bicyclette` date NOT NULL,
`Nom_Bicyclette` varchar(255) DEFAULT NULL,
`Grandeur_Bicyclette`
enum('Dames','Hommes','Garçons','Filles','Adultes','Jeunes') DEFAULT NULL,
PRIMARY KEY (`ID_Bicyclette`),
KEY `ID_Assemblage` (`ID_Assemblage`),
CONSTRAINT `ID_Assemblage` FOREIGN KEY (`ID_Assemblage`) REFERENCES `Assemblage` (`ID_Assemblage`) ON DELETE CASCADE ON UPDATE CASCADE
)
Trigger Action :
I would like that when a new row is inserted into Bicyclette with as values :
the foreign key referring to a row of Assemblage
the values of the all the others attributes except 'Nom_Bicyclette' and 'Grandeur_Bicyclette' which will be null.
that a Trigger inserts 'Nom_Bicyclette' and 'Grandeur_Bicyclette' with the corresponding data from Assemblage thanks to the Foreign Key ID_Assemblage
Here is an example of inserting data into Bicyclette:
INSERT INTO Bicyclette VALUES (102, 547.8, "VTT", 01/01/2022, 01/01/2023)
Where 102 is the assembly model in the table Assemblage.
So i would like my Trigger to perform this action (for this example):
DECLARE #name VARCHAR
DECLARE #size VARCHAR
#name = SELECT Nom_Assemblage FROM Assemblage WHERE ID_Assemblage = 102
#size = SELECT Grandeur_Assemblage FROM Assemblage WHERE ID_Assemblage = 102
UPDATE Bicyclette SET Nom_Bicyclette=#name, Grandeur_Bicyclette=#size
WHERE ID_Bicyclette = INSERTED.ID_Bicyclette
Here is a diagram to better visualize the desired effect :
Schema for trigger
Thank you in advance for your help!
(It may seem special, but I have to have the fields 'Nom_Bicyclette' and 'Grandeur_Bicyclette' which correspond to the Foreign Key ID_Assemblage in my Bicyclette Table.)
create trigger Bicyclette_copy_attributes
before insert on Bicyclette
for each row begin
declare name varchar(255);
declare size varchar(255);
select Nom_Assemblage, Grandeur_Assemblage into name, size from Assemblage
where ID_Assemblage = NEW.ID_Assemblage;
set NEW.Nom_Bicyclette = name;
set NEW.Grandeur_Bicyclette = size;
end
In MySQL, there are differences in the syntax from other brands of SQL database:
DECLARE variables do not use the # sigil.
Use a BEFORE trigger if you need to change columns in the inserted row. If you write an AFTER trigger, it is too late, because the row has already been inserted.
Change columns with SET NEW.<column>, not UPDATE. The NEW keyword references the row that is about to be inserted.
All statements in the body of the trigger need to be terminated with a semicolon (;).
Also read https://dev.mysql.com/doc/refman/8.0/en/stored-programs-defining.html if you are using the MySQL client to execute the create trigger, so you understand how to set the delimiter.
I'm using MySQL Workbench.
I would like to create a table named courseInfo and I want to put a column named moduleCode in it, but I want it to always be similar in format: CFSM H0000 where the four zeros are a number that increases starting with 0000.
For example:
CFSM H0001
CFSM H0002
[..]
You cannot auto-increment character type columns in MySQL, as auto-increment is only possible on integer type columns. One (alphanumeric) auto-incrementing moduleCode column would therefore not be possible. However, you could try splitting up the moduleCode into two columns, for example like so:
CREATE TABLE `courseInfo` (
`prefix` CHAR(6) NOT NULL DEFAULT 'CFSM H',
`id` SMALLINT(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
KEY (`id`)
) AUTO_INCREMENT = 0;
Where prefix could for example be "CFSM H" and id could be 0001
Then, upon executing SELECT statements, you could merge the prefix column with the id column into a moduleCode column with CONCAT, e.g.:
SELECT CONCAT(`prefix`, `id`) as `moduleCode` FROM `courseInfo`;
An alternative approach (from MySQL version 5.7 and up) seems to be the use of a generated column, for example:
CREATE TABLE `courseInfo` (
`prefix` CHAR(6) NOT NULL DEFAULT 'CFSM H',
`id` SMALLINT(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
`moduleCode` CHAR(10) AS (CONCAT(`prefix`, `id`)),
KEY (`id`)
) AUTO_INCREMENT = 0;
However, the above example of a generated column would not work, because moduleCode is dependent on an auto-increment column, and the auto-increment is not executed yet at the time the generated column is computed. See also: https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html. It would throw an ER_GENERATED_COLUMN_REF_AUTO_INC error.
You could therefore use the first solution, or try to add moduleCode as a column and use an AFTER INSERT trigger to update its value:
CREATE TABLE `courseInfo` (
`prefix` CHAR(6) NOT NULL DEFAULT 'CFSM H',
`id` SMALLINT(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
`moduleCode` CHAR(10),
KEY (`id`),
UNIQUE KEY `unique_index` (`prefix`,`id`)
) AUTO_INCREMENT = 0;
DELIMITER //
CREATE TRIGGER `addModuleCode` AFTER INSERT ON `courseInfo`
FOR EACH ROW
BEGIN
UPDATE `courseInfo` SET `moduleCode` = CONCAT(NEW.`prefix`, NEW.`id`) WHERE `prefix` = NEW.`prefix` AND `id` = NEW.`id`;
END;//
DELIMITER ;
I want to create a table name Users where I should have have columns User, cookieID, sessionID, Geo and then I want to first three columns to have some random unique value assigned automatically. I tried to make all three columns AUTO_INCREMENT with User column PRIMARY and 'cookieIDandsessionIDcolumnUNIQUE`. The SQL code is:
CREATE TABLE `users` ( `User` VARCHAR(20) NOT NULL AUTO_INCREMENT ,
`cookieID` INT(20) NULL DEFAULT NULL AUTO_INCREMENT ,
`sessionID` INT(20) NULL DEFAULT NULL AUTO_INCREMENT ,
`Geo` VARCHAR(30) NULL DEFAULT NULL ,
PRIMARY KEY (`User`), UNIQUE (`cookieID`), UNIQUE (`sessionID`), UNIQUE (`Geo`));
But, it did not work because only one column can be declared as AUTO_INCREMENT which must be PRIMARY.
What is the another approach to do this?
Since the auto-increment cannot be applied to multiple to rows and there no option for sequence in MySQL. You can use triggers for the unique update of the row with datetime.
Change to table creation to be of single auto-increment row.
CREATE TABLE `users` ( `User` VARCHAR(20) NOT NULL,
`cookieID` INT(20) NULL DEFAULT NULL,
`sessionID` INT(20) NULL DEFAULT NULL AUTO_INCREMENT ,
`Geo` VARCHAR(30) NULL DEFAULT NULL,
PRIMARY KEY (`User`), UNIQUE (`cookieID`), UNIQUE (`sessionID`), UNIQUE (`Geo`));
Create a trigger on the same table as below. You can set the unique values under the SET for as many column as you want.
CREATE DEFINER=`root`#`localhost` TRIGGER `users_BEFORE_INSERT` BEFORE INSERT ON `users` FOR EACH ROW BEGIN
SET
NEW.cookieID = (SELECT curdate()+curtime());
END
Now when you insert into the table as below.
insert into `users`(`User`) values("test");
You table looks like this.
User cookieID sessionID Geo
test 20315169 0 NULL
If the value which are auto incrementing, you wanna keep both values the same. Then copy the value of one column to another during insertion time of new value.
I have a table in which there is a column name with SP varchar(10) NOT NULL. I want that column always to be unique so i created unique index on that column . My table schema as follows :
CREATE TABLE IF NOT EXISTS `tblspmaster` (
`CSN` bigint(20) NOT NULL AUTO_INCREMENT,
`SP` varchar(10) NOT NULL,
`FileImportedDate` date NOT NULL,
`AMZFileName` varchar(50) NOT NULL,
`CasperBatch` varchar(50) NOT NULL,
`BatchProcessedDate` date NOT NULL,
`ExpiryDate` date NOT NULL,
`Region` varchar(50) NOT NULL,
`FCCity` varchar(50) NOT NULL,
`VendorID` int(11) NOT NULL,
`LocationID` int(11) NOT NULL,
PRIMARY KEY (`CSN`),
UNIQUE KEY `SP` (`SP`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10000000000 ;
Now i want that if anybody tries to insert duplicate record then that record should be inserted into a secondary table name tblDuplicate.
I have gone through this question MySQL - ignore insert error: duplicate entry but i am not sure that instead of
INSERT INTO tbl VALUES (1,200) ON DUPLICATE KEY UPDATE value=200;
can i insert duplicate row into another table ?
what changes needed to be done in main table scheme or index column ?
**Note : Data will be inserted by importing excel or csv files and excel files generally contains 500k to 800 k records but there will be only one single column **
I believe you want to use a trigger for this. Here is the MySQL reference chapter on triggers.
Use a before insert trigger. In the trigger, check if the row is a duplicate (maybe count(*) where key column value = value to be inserted). If the row is a duplicate, perform an insert into your secondary table.
I want to copy all the fields from the temp_sales table to sales table (after specific field). I want to do it quickest way as possible.. How to do this in SQL?
CREATE TABLE IF NOT EXISTS `temp_sales` (
`field1` varchar(10) NOT NULL,
`field2` varchar(20) NOT NULL,
`field3` varchar(20) NOT NULL,
`field4` varchar(50) NOT NULL,
`field5` varchar(50) NOT NULL,
`field6` varchar(50) NOT NULL,
`field7` varchar(50) NOT NULL,
`field8` tinyint(2) NOT NULL,
`field9` tinyint(2) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=13692 ;
In other word: There are some fields in the sales table. I want to add more new fields in the sales table from temp_sales (without data).
This is a 3-Step process:
.1. You need some unique or primary key field in temp_sales, that links a row in temp_sales to the corresponding row in sales (again via a unique/primary key)
.2. You need a DDL statement such as
ALTER TABLE `sales`
ADD COLUMN `field1`VARCHAR(10) AFTER `whatever`,
ADD COLUMN `field2`VARCHAR(10) AFTER `fields2`,
...
.3. You need a DML statement such as
UPDATE `sales`
INNER JOIN `temp_sales` ON `sales`.`keyfield`=`temp_sales`.`keyfield`
SET `sales`.`field1`=`tempsales`.`field1`,
`sales`.`field2`=`tempsales`.`field2`,
...
You can do this:
mysql> create table new_table_name as(select * from existing_table_name);
//It will also populate existing table data to new table if present
//If old table is empty then it will create same copy of that table
In your case:
mysql> create table sales as(select * from temp_sales);