I put 10,000 avatar photos on a server and I would like for each row inserted into the 'studenttable' table, the 'photo' column to be the concatenation of the url of the folder of my photos + the id of the inserted student.
However, the CONCAT function returns a NULL value with the basic trigger used.
First, here is the above mentioned table :
CREATE TABLE `studenttable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`gender` enum('Male','Female','Other') NOT NULL,
`email` varchar(100) DEFAULT NULL,
`birthDate` date DEFAULT NULL,
`photo` varchar(535) DEFAULT NULL,
`mark` double DEFAULT NULL,
`comment` varchar(535) DEFAULT NULL,
PRIMARY KEY (`id`)
)
and here is the basic trigger I created:
DELIMITER $$
create trigger IMAGE_LienApi
before insert on studenttable
for each row
begin
set NEW.photo = CONCAT('https://url-of-folder-with-my-images/',NEW.id,'.png');
end$$
DELIMITER ;
For information, the images are referenced in this way:
number.png
So when I insert a new student with this trigger, the photo column is always set to NULL.
The problem must come from NEW.id, because when I replace this value with a string, it works.
I also tried with
NEW.photo = 'https://url-of-folder-with-my-images/' + CONVERT(VARCHAR(5),NEW.id),'.png';
but it did not work
Thank you in advance for your help and if someone could explain to me especially why the CONCAT does not work, that would be great !
CONCAT() returns NULL if any of its arguments are NULL.
In a BEFORE INSERT trigger, the NEW.id value is NULL. It hasn't been generated yet.
But in an AFTER INSERT trigger, it's too late to change the NEW.photo column of your row. You can't change columns in an AFTER trigger.
You cannot make a BEFORE INSERT trigger to concatenate an auto-increment value with other columns. The best you can do is let the INSERT complete, and then subsequently do an UPDATE to change your photo column.
The alternative is to forget about using the builtin AUTO_INCREMENT to generate id values, instead generate them some other way and specify the value in your INSERT statement.
Related
I'm new to MySQL & I try to enter records to mysql table. I'm getting following error
INSERT INTO advertising.discountauthorizationrequst SET DARDateTime=cast('2003-01-13 16:50:32' as datetime), `DARPubCode`=trim('DD'), `DARPubDate`=cast('2022-05-08' as date), `DARAutUser`=trim("U0001"), `DARDeviceID`=trim('123456789ABCDEFGHIJKL987456'), `DARMessage`=trim("This Is Test Message"), `DARGranted`=("0"), `DARUser`=trim("DATAENTRYUSERNAME") Error Code: 1054. Unknown column 'DARDateTime' in 'field list'
I listed my INSERT statement below. Someone please help me to solve this issue. I'm using mysql workbench 8.0.
Columns:
DARDateTime datetime PK
DARPubCode varchar(3) PK
DARPubDate date PK
DARAutUser varchar(5)
DARDeviceID varchar(50)
DARMessage varchar(100)
DARGranted varchar(1)
DARUser varchar(50) PK
Here is script
INSERT INTO `advertising`.`discountauthorizationrequst`
SET
`DARDateTime`=cast('2003-01-13 16:50:32' as datetime),
`DARPubCode`=trim('DD'),
`DARPubDate`=cast('2022-05-08' as date),
`DARAutUser`=trim("U0001"),
`DARDeviceID`=trim('123456789ABCDEFGHIJKL987456'),
`DARMessage`=trim("This Is Test Message"),
`DARGranted`=("0"),
`DARUser`=trim("DATAENTRYUSERNAME");
Edited..
Table Inspactor - DDL
CREATE TABLE `discountauthorizationrequst` (
`DARDateTime` datetime NOT NULL,
`DARPubCode` varchar(3) NOT NULL,
`DARPubDate` date NOT NULL,
`DARAutUser` varchar(5) DEFAULT NULL,
`DARDeviceID` varchar(50) DEFAULT NULL,
`DARMessage` varchar(100) DEFAULT NULL,
`DARGranted` varchar(1) DEFAULT NULL,
`DARUser` varchar(50) NOT NULL,
PRIMARY KEY (`DARDateTime`,`DARPubCode`,`DARPubDate`,`DARUser`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
You are actually confusing the SQL commands and coming up with a hybrid of them. The INSERT command most commonly is done in two ways..
insert into SomeTable
( these, columns )
values
( oneValue, anotherValue)
or
insert into SomeTable( these, columns )
select oneColumn, secondColumn
from SomeOtherTable
where SomeCondition
The UPDATE command is based on an EXISTING record that you want to change
Update SomeTable set
thisColumn = SomeValue,
anotherColumn = SomeOtherValue
where SomeCondition
So, what you appear to be doing would be written as
INSERT INTO advertising.discountauthorizationrequst
( DARDateTime,
DARPubCode,
DARPubDate,
DARAutUser,
DARDeviceID,
DARMessage,
DARGranted,
DARUser
)
values
(
cast('2003-01-13 16:50:32' as datetime),
'DD',
'2022-05-08',
'U0001',
'123456789ABCDEFGHIJKL987456',
'This Is Test Message',
'0',
'DATAENTRYUSERNAME'
)
Notice the readability with formatting, you can see each column that is needed followed by the explicit values (which could be parameterized during code later) are in the same ordinal context. So, if you ever needed to add a new column to the insert, easy to do with the same ordinal position in the values provided secondarily to it.
As for the 3rd column, by providing a string in YYYY-MM-DD, SQL typically auto-converts to a date format. Other fields, you dont need to explicitly TRIM() everything. If parameterized, you would pass the trimmed VALUE, when you get to that point in your development.
I found the mistake that I made. I created triggers for the above table. After I deleted those triggers its working.
I am having an issue with a trigger I have put in a database I am building. It is the only trigger in the database. Here are the two tables being used.
Client Table
create table client (
clientNum INT(5) not null auto_increment,
clientName TEXT(30) not null,
clientEmail VARCHAR(64) not null,
clientGender CHAR(1) not null,
clientDOB DATE not null,
clientAddress TEXT(50),
clientPhone VARCHAR(12) not null,
hasInsurance CHAR(1) not null,
clientBalanceOwed DECIMAL(10,2),
clientLastDateVisited DATE,
clientNextVisitDate DATE,
primary key (clientNum));
Insurance Table
create table insurance(
insuranceNum INT(5) not null auto_increment,
cardNum INT(16),
policyNum INT(6),
policyHolder TEXT(30),
clientNum INT(5),
primary key (insuranceNum),
foreign key (clientNum) references client(clientNum));
The idea for the following trigger is to only create an insurance row when a client is added to the database that has the 'hasInsurance' field set to 'y'. Then, once that client has been added, create a new insurance row with the clientNum set to the clientNum that was just added.
The Trigger
delimiter $$
create trigger New_Insurance_Row after insert on client
for each row
begin
if(client.hasInsurance = 'y') then
insert into insurance (clientNum) values (NEW.clientNum);
end if;
end$$
Everything up to this point works as intended, until you try to insert a new client into the table and call the trigger. Once I try and add the following line of code:
The Insert Statement
insert into client(clientName, clientEmail, clientGender, clientDOB,
clientAddress,
clientPhone, hasInsurance, clientBalanceOwed, clientLastDateVisited,
clientNextVisitDate)
values
('Darcy Watts','dwatts#email.com','m','1996-5-9','Belfast, Charlottetown
PEI','123-222-3333','y','400.77','2017-8-12','2019-9-6');
When I try and run this I am met with this error:
#1109 - Unknown table 'client' in field list
So from what I've learned over the last few hours is that this error usually happens when you put the '`' (backtick) on a variable or table name, MySQL thinks that entry is part of a field list or something along that line. So I changed the trigger to just be 'client' by itself and I still got an error. Dropped the old database and everything. One more thing, the insert statement does work by itself if the trigger has not been entered yet.
Any help would be appreciated! Thanks!
I guess your hasInsurance should be from the new record.
...
if(new.hasInsurance = 'y') then
insert into insurance (clientNum) values (NEW.clientNum);
end if;
...
--
DB Fiddle (provided by GMB)
I am trying to create a fairly complicated Trigger and I'm not sure if it can be done on phpMyAdmin.
Right now I have this query that creates a table with all the information I need from it.
CREATE TABLE SeniorDB_Shipping
SELECT
SeniorDB_Invoice.ID_Order,
SeniorDB_Customer.MCT_Code,
SeniorDB_Customer.Customer_Name,
SeniorDB_Customer.Customer_Address,
SeniorDB_Customer.Customer_City,
SeniorDB_Customer.Customer_State,
SeniorDB_Invoice.Shipping_Company
FROM SeniorDB_Customer
Join SeniorDB_Invoice ON SeniorDB_Customer.MCT_Code = SeniorDB_Invoice.MCT_Code
As you can see in the image, when I run the query, it pulls in information from the tables above the information. I'm trying (and failing) to create a trigger that will do this same thing without having to create a brand new table every single time. All the other posts I have seen are similar in regards to creating a table instead of inserting to a table.
What the trigger does is, when I enter the ID_Order, the rest of the information will get pulled from the database.
This is the trigger I have so far:
delimiter ~
create trigger SeniorDB_Shipping before insert on SeniorDB_Shipping
for each row begin
set new.SeniorDB_Shipping.MCT_Code = new.SeniorDB_Customer.MCT_Code,;
set new.SeniorDB_Shipping.Customer_Name = new.SeniorDB_Customer.Customer_Name,;
set new.SeniorDB_Shipping.Customer_Address = new.SeniorDB_Customer.Customer_Address,;
set new.SeniorDB_Shipping.Customer_City = new.SeniorDB_Customer.Customer_City,;
set new.SeniorDB_Shipping.Customer_State = new.SeniorDB_Customer.Customer_State,;
set new.SeniorDB_Shipping.Shipping_Company = new.SeniorDB_Customer.Shipping_Company,;
end~
delimiter ;
I feel like I'm right there. I just can't link it to when I enter the ID_Order.
This is the page if you would like to see the databases: http://polonium.forest.usf.edu/~sngamwon/SeniorProject/SeniorDB_Order.php
Ok, so you'll need to run this once:
/* Create the table with a primary key */
create table `SeniorDB_Shipping` (
`id` INT unsigned AUTO_INCREMENT NOT NULL,
primary key(id),
`ID_Order` int NOT NULL,
`MCT_Code` int NOT NULL,
`Customer_Name` varchar(255) NOT NULL,
`Customer_Address` varchar(255) NOT NULL,
`Customer_City` varchar(255) NOT NULL,
`Customer_State` varchar(255) NOT NULL,
`Shipping_Company` varchar(255) NOT NULL
) ENGINE=MyISAM CHARACTER SET=utf8 COLLATE utf8_general_ci;
Then you can run
/* Insert statement */
INSERT INTO `SeniorDB_Shipping` (
`ID_Order`,
`MCT_Code`,
`Customer_Name`,
`Customer_Address`,
`Customer_City`,
`Customer_State`,
`Shipping_Company`
) SELECT
invoice.ID_Order,
customer.MCT_Code,
customer.Customer_Name,
customer.Customer_Address,
customer.Customer_City,
customer.Customer_State,
invoice.Shipping_Company
FROM
SeniorDB_Customer as customer
Join SeniorDB_Invoice as invoice
ON customer.MCT_Code = invoice.MCT_Code;
I've run this in my own PHPMyAdmin, so it works. But I obviously don't have your schema. Known issues:
This will populate SeniorDB_Shipping with ALL the data from your two tables each time. Modify the query as required to select only recent data if that's not what you want. If ID_Order is a primary key you could check that doesn't already exist.
I want to create a column with default value as null and when any operation is performed it should change to 0. How do i do this in mysql database?
Here example how to add colum in existing table with default value
ALTER TABLE `test1` ADD `no` INT NULL DEFAULT NULL ;
When you call function then you have to write following query
UPDATE test1 SET `no` = '0' WHERE `test1`.`id` =your_id;
CREATE TABLE test
(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
test_id INT,
cost FLOAT(5,2) DEFAULT NULL,
);
each time when you do some operation on that you need to update it as #Sadikhasan
or write a trigger that will update it to zero automatically.
if the operation you want to perform is read then write trigger on ON SELECT
if the operation you want to perform is update then write trigger on ON UPDATE
like wise for others.
I am trying to figure out make a trigger to assign the value of the auto incremented 'ID' primary key field that is auto generated upon insert to another field 'Sort_Placement' so they are the same after insert.
If you are wondering why I am doing this, 'Sort_Placement' is used as a sort value in a table that can be changed but by default the record is added to the bottom of the table
Table Data
`ID` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`Account_Num` mediumint(8) unsigned NOT NULL,
`Product_Num` mediumint(8) unsigned NOT NULL,
`Sort_Placement` mediumint(8) unsigned DEFAULT NULL,
`Order_Qty_C` smallint(6) NOT NULL DEFAULT '0',
`Order_Qty_B` smallint(6) NOT NULL DEFAULT '0',
`Discount` decimal(6,2) NOT NULL DEFAULT '0.00',
PRIMARY KEY (`ID`),
UNIQUE KEY `ID_UNIQUE` (`ID`)
After Insert Trigger
CREATE
TRIGGER `order_guide_insert_trigger`
AFTER INSERT ON `order_guide`
FOR EACH ROW
BEGIN
IF Sort_Placement IS NULL THEN
SET Sort_Placement = NEW.ID;
END IF;
END;
I have tried a bunch of combinations of using the "NEW" prefix with no luck. For example putting the NEW prefix before each field name.
Trying it out
INSERT INTO `order_guide` (`Account_Num`, `Product_Num`) VALUES ('5966', '3');
Insert Error
ERROR 1054: Unknown column 'Sort_Placement' in 'field list'
This seems like a bit of a hack job but I was able to get it working using the LAST_INSERT_ID() function built into MySQL.
CREATE TRIGGER `order_guide_insert_trigger`
BEFORE INSERT ON `order_guide`
FOR EACH ROW
BEGIN
IF NEW.Sort_Placement IS NULL THEN
SET NEW.Sort_Placement = LAST_INSERT_ID() + 1;
END IF;
END;
This also works and seems to work
CREATE TRIGGER `order_guide_insert_trigger`
BEFORE INSERT ON `order_guide`
FOR EACH ROW
BEGIN
IF NEW.Sort_Placement IS NULL THEN
SET NEW.Sort_Placement = (SELECT ID FROM order_Guide ORDER BY id DESC LIMIT 1) + 1;
END IF;
END;
I ran into a similar (yet different) requirement, where a field value in the table needed to be based on the new record's Auto Increment ID. I found two solutions that worked for me.
The first option was to use an event timer that runs every 60 seconds. The event updated the records where my field was set to the default of null. Not a bad solution if you don't mind the up to 60 second delay (you could run it every 1 second if the field that is being update is indexed). Basically the event does this:
CREATE EVENT `evt_fixerupper`
ON SCHEDULE EVERY 1 MINUTE
ENABLE
COMMENT '' DO
BEGIN
UPDATE table_a SET table_a.other_field=CONCAT(table_a.id,'-kittens')
WHERE ISNULL(table_a.other_field);
END;
The other option was to generate my own unique primary IDs (rather than relying upon AUTOINCREMENT. In this case I used a function (in my application) modeled after the perl module https://metacpan.org/pod/Data::Uniqid. the generated ID's are huge in length, but they work well, and I know the value before I insert, so I can use it to generate values for additional fields.