Multiple Queries in Triggers - mysql

I'm fairly new to using triggers and have a tiny question.
I have a trigger finds a match between a newly inserted enquiry and a customer table.
INSERT INTO customersmatched (customerID,enquiryID) SELECT id, NEW.id FROM customer AS c WHERE c.customerName=NEW.companyName HAVING COUNT(id)=1;
I then need to update the newly inserted enquiry so it has a status which shows it's matched (but only if it has matched). So I tried adding this line after the insert.
UPDATE enquiry SET status="Live-Enquiry" WHERE id IN ( SELECT enquiryID FROM customersmatched WHERE enquiryID = NEW.id);
Except I get this error:
MySQL said: #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 'UPDATE enquiry SET status="Live-Enquiry" WHERE id
IN ( SELECT enquiryID FROM cus' at line 5
How do I allow multiple queries within a trigger. I've tried doing something like in this link: Multiple insert/update statements inside trigger?
But doesn't work either. I'm using phpmyadmin btw. Can anyone help? :D

If you have ansi quotes enabled then you can't use double quotes as a string literal, and need to use single quotes instead. see: http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_ansi_quotes Otherwise, I don't see any syntax errors that jump out at me.
Try changing SET status="Live-Enquiry" to SET status='Live-Enquiry'
EDIT:
What is the purpose of the first query? I'm not sure you need the HAVING in that query. If want a distinct list of matches, just use DISTINCT
INSERT INTO customersmatched (customerID,enquiryID)
SELECT DISTINCT id, NEW.id
FROM customer AS c
WHERE c.customerName=NEW.companyName;
The second query, if I understand it correctly, can be simplified to this:
UPDATE enquiry
SET status='Live-Enquiry'
WHERE id = NEW.id;

Related

MySql create record with IF statement

SQL Query Forum 20210309
I’m building a Firebase Functions application that talks to a Google Cloud SQL database running MySQL 5.7. I’m trying to retrieve a value from a row in one table and, if it exists (the row or the value), insert a record in a different table.
Based on some examples I found online, my code looks like this:
DECLARE meeting_link varchar(2048) DEFAULT ""; SELECT meeting_link from campaigns where id=2 INTO meeting_link; IF LENGTH(meeting_link) > 0 THEN INSERT INTO clicks (target_id, ip_address, user_agent) VALUES (38, "ip-address", "user-agent") END IF;
In all of the different versions of this I tried, I get an error:
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 'DECLARE meeting_link varchar(2048) DEFAULT ""; SELECT meeting_link from campaigns' at line 1
Looking around some more, I found posts that say I can’t use DECLARE in anything but stored procedures, but I can use local variables (#ml for example) but I can’t seem to get that working correctly either.
Can someone please help me with the SQL I need for this? I need to create the record only if the record in the query exists and return the meeting_link value to my calling program.
Refer to this documentation page:
https://dev.mysql.com/doc/refman/8.0/en/sql-compound-statements.html
This section describes the syntax for the BEGIN ... END compound statement and other statements that can be used in the body of stored programs
That includes DECLARE and also IF/THEN/ELSE/END constructions. You can't use those outside of stored routines.
Here's a trick you can use instead of a stored routine:
SELECT meeting_link from campaigns where id=2 INTO #meeting_link;
INSERT INTO clicks (target_id, ip_address, user_agent)
SELECT 38, 'ip-address', 'user-agent' FROM dual WHERE LENGTH(#meeting_link) > 0;
You can use #meeting_link which is a user-defined variable, not a declared local variable.
Then instead of using IF, use FROM dual WHERE ... for your condition. The dual table is normally a pseudo-table that doesn't really exist but querying it returns 1 row. But you can make that zero rows if the condition in the WHERE clause isn't satisfied.
So the INSERT will conditionally create either one or zero rows.
Re your comment:
If you need this to be done in a single SQL statement, then one option would be to make that single SQL statement CALL a procedure that you create in your MySQL database. Then at least you could use DECLARE and IF like you were intending.
Another alternative is to combine the two statements I show above like this:
INSERT INTO clicks (target_id, ip_address, user_agent)
SELECT 38, 'ip-address', 'user-agent'
FROM campaigns WHERE id=2 AND LENGTH(meeting_link) > 0;
This works because even though you query the campaigns table, it's not mandatory to select the columns of that table. You can select constant values instead. The conditions in the WHERE clause will make this return either one row or zero rows.

Syntax Error in MYSQL clausules

Hello stackoverflow's friends i need your help with this sql clausule this is the error into mysql:
_mysql_exceptions.ProgrammingError: (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 'WHERE email='Tysaic0344#gmail.com'' at line 1")
and this is my code:
INSERT INTO user (token) VALUES (1) WHERE email='example#email.com'
You cannot insert values into an existing row. You can either update or delete the existing records. In your case, I think you want to update the existing row. You can use UPDATE.
UPDATE user SET token = 1 WHERE email = 'example#email.com';
If you want to add records to the table use INSERT
INSERT INTO user VALUES (1, 'example#email.com');
Here is the link for your reference
https://msdn.microsoft.com/en-us/library/bb243852(v=office.12).aspx
You can't INSERT with a WHERE clause.
If you need to UPDATE the record where you have the email from:
UPDATE user
Set token = 1
WHERE email='example#email.com'
Or INSERT with email
INSERT INTO user (token, email)
VALUES (1, 'example#email.com')
(or without)
INSERT INTO user (token)
VALUES (1)
These kind of errors you MUST be able to fix by yourself, the error even tells you where it went wrong (at the end it says "near 'WHERE...").
Check the docs that dns_nx included (especially https://dev.mysql.com/doc/refman/5.7/en/update.html ) for the correct syntax to do an update.
You cannot INSERT a value into an existing row. The WHERE clause is invalid with INSERT. If you want to update an existing row, then you have to UPDATE the field like this:
UPDATE
user
SET
token = 1
WHERE
email='example#email.com'
Please review the docs about INSERT and UPDATE
https://dev.mysql.com/doc/refman/5.7/en/update.html
https://dev.mysql.com/doc/refman/5.7/en/insert.html
INSERT inserts new rows into a table. The WHERE clause is used to filter existing rows from a table. It doesn't make sense in a INSERT query; that's why the INSERT statement does not contain a WHERE clause.
The WHERE clause is used to filter the rows to fetch from the table (the SELECT statement), the rows to modify (the UPDATE statement) or to remove from the table (the DELETE statement).
Your query looks like you want to modify the data already existing in the table. The UPDATE statement you need looks like this:
UPDATE user SET token = 1 WHERE email = 'example#email.com'

I have a syntax error in my code for creating a trigger using sql. I use mysql version 14.14

Hey Guys I have a syntax error in my trigger I dont know why! I have 3 tables in a database for a sales company, namely ORDERS,SALESREPS AND PRODUCTS. Whenever an order is placed, I have to add that order to ORDERS table. The cost of the order is added to the SALES column in SALESREPS table. Note that salesreps is a table of people who sell products and the column sales stores total amount of sales by respective salesperson. Also, The table PRODUCTS( which is a table having a list of all products and their details) contains a column 'quantity in hand'. SO when an order is placed, I have to reduce the number of orders from the quantity available before order of that product was placed.
I get a syntax error as
ERROR 1064 (42000): 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 'ON ORDERS AFTER INSERT AS
UPDATE SALESREPS
SET SALES=SALES+INSERTED.AMOUNT' at line 2
Here is my code for trigger:
CREATE TRIGGER test_trigger
ON ORDERS AFTER INSERT AS
UPDATE SALESREPS
SET SALES=SALES+INSERTED.AMOUNT
FROM SALESREPS,INSERTED
WHERE SALESREPS.EMPL_NUM=INSERTED.REP;
UPDATE PRODUCTS
SET QTY_ON_HAND=QTY_IN_HAND - INSERTED.QTY
FROM PRODUCTS,INSERTED
WHERE PRODUCTS.MFR_ID=INSERTED.MFR
AND PRODUCTS.PRODUCT_ID=INSERTED.PRODUCT;
Also, since my am updatin tables based on a inserted tuple , how do I refer to the inserted tuple??
You have multiple syntax problem here, but I think this is what you need
DELIMITER $$
CREATE TRIGGER test_trigger
AFTER INSERT ON ORDERS
FOR EACH ROW BEGIN
UPDATE SALESREPS
SET SALES=SALES+NEW.AMOUNT
WHERE SALESREPS.EMPL_NUM=NEW.REP;
UPDATE PRODUCTS
SET QTY_ON_HAND= (QTY_IN_HAND - NEW.QTY)
WHERE PRODUCTS.MFR_ID=NEW.MFR_ID
AND PRODUCTS.PRODUCT_ID=NEW.PRODUCT;
END;$$
DELIMITER ;
Your first problem was with this line :
ON ORDERS AFTER INSERT AS
Which is reverted, it need to be
AFTER INSERT ON ORDERS
Notice that I removed the AS.
You were also missing the FOR EACH ROW BEGIN/END 
Notice that at the beginning I specify the delimiters to be $$ so the compiler know when to stop.
Also, update statement must not have a from clause, as you already specify which table you are updating on the first statement.
UPDATE SALESREPS
Next problem is when you tried to refer to the new value, well the specified keyword to access is is as simple as new.
Your last error was your condition where products.mfr_id = new.mfr you probably just made a typo here, you want to use where products.mfr_id = new.mfr_id

Learning MySQL, Python - Skip Duplicates

I've been trying to learn SQL using python to update a db and am trying to do something simple. Iterate through a csv file that includes the fortune 500 with their revenue info and push into an SQL db. I've run it a few times and it's working great, the only issue is I'm getting duplicates because I've run the same file a few times.
In the future, I'm assuming it's good to learn how to avoid duplicates. After looking around this is what I've found for a proposed solution using WHERE NOT EXISTS but am getting an error. Any advice is welcome as I'm totally new.
Note - I do know I should be updating more than one row at a time, that's my next lesson
import pymysql
import csv
with open('companies.csv','rU') as f:
reader = csv.DictReader(f)
for i in reader:
conn = pymysql.connect(host='host', user='user', passwd='pw', db='db_test')
cur = conn.cursor()
query1 = "INSERT INTO companies (Name, Revenue, Profit, Stock_Price) VALUES (\'{}\',{},{},{})".format(str(i['Standard']),float(i['Revenues']),float(i['Profits']),float(i['Rank']))
query2 = 'WHERE NOT EXISTS (SELECT Name FROM companies WHERE Name = \'{}\')'.format(str(i['Standard']))
query = query1+' '+query2
cur.execute(query)
conn.commit()
cur.close()
OUTPUT:
INSERT INTO companies (Name, Revenue, Profit, Stock_Price) VALUES ('WalMart Stores',469.2,16999.0,1.0) WHERE NOT EXISTS (SELECT Name FROM companies WHERE Name = 'WalMart Stores')
ERROR:
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 'WHERE NOT EXISTS (SELECT Name FROM companies WHERE Name = 'WalMart Stores')' at line 1")
Ok. First of all, congratulations on self-learning!
Now, to the point.
When you use insert ... values, you can't define a where condition for the table on which you're inserting values. insert statement is only used to insert (When you use insert... select, you can define a where condition on the select, not on the table on which you're about to insert values).
So, there are two ways to do what you want:
Create a unique index on the column that you want to test, and then use insert ignore...
In your code, check if the value is already there, and if it's not, then insert it.
I'll tell you how to work with the first suggestion, because it'll teach you a couple of things. As for suggestion 2, I'll leave that for you as homework ;-)
First, you need to add a unique index to your table. If you want to avoid duplicates on the Name column, then:
alter table companies
add unique index idx_dedup_name(Name);
Check the syntax for ALTER TABLE.
And now, let's say that Companies already has a row with name 'XCorp'. If you try a normal INSERT... VALUES statement here, you'll get an error, because you're trying to add a duplicate value. If you want to avoid that error, you can use something like this:
insert ignore into companies(name) values ('XCorp');
This will execute as a normal insert, but, since you're trying to insert a duplicate value, it will fail, but silently (it wil throw a warning instead of an error).
As for suggestion 2, as I told you, I leave it to you as homework.
Hints:
Count the rows where the name matches a value.
Read the count to a variable in your python program
Test the value... if there's zero entries, then perform the insert.

MySQL syntax error regarding WHERE NOT EXISTS

I have a Chef recipe for creating Unix user IDs and deploying them across multiple nodes, to guarantee uniqueness and prevent devs from having to track them themselves. They merely name the application and it is granted a unique ID if an ID for that application doesn't already exist. If one does, it is simply returned to the script and user accounts are created on the webservers with the appropriate value.
I have a mysql database with a single table, called application_id_table which has two columns, id and application_name. id is autoincrementing and application name cannot be null (and must be unique).
Removing the Ruby from my script and making a couple of substitutions, my sql looks like this:
INSERT INTO application_id_table(application_name) VALUES('andy_test')
WHERE NOT EXISTS (select 1 from application_id_table WHERE
application_name = 'andy_test');
when run, I receive the syntax parsing error:
ERROR 1064 (42000): 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 'WHERE NOT EXISTS (select 1 from
application_id_table WHERE application_name = 'a'
I recall seeing that the values statement does not allow a where clause but I don't wish to use a select statement to populate the values as I'm populating them from variables supplied from within Ruby/Chef. Anyone have an idea how to accomplish this?
You want to use insert . . . select:
INSERT INTO application_id_table(application_name)
SELECT aname
FROM (SELECT 'andy_test' as aname) t
WHERE NOT EXISTS (select 1 from application_id_table ait WHERE ait.application_name = t.aname);
You should be able to plug your variable directly into the select statement, the same you would would with the VALUES statement.
Try this:
INSERT INTO application_id_table(application_name)
select 'andy_test'
WHERE NOT EXISTS (select 1 from application_id_table WHERE application_name = 'andy_test');