I want to update a record if it exists or create a new record if it does not exist yet but somehow it is throwing an error and I cannot find out why..
I want to update the status of a customer if it exists or create a new customer if not exist.
my query:
$sql = "SELECT CASE WHEN EXISTS ( SELECT * FROM sms WHERE number = '123456789' AND customer_id = '1' ) THEN UPDATE sms SET stat = '1' ELSE INSERT INTO sms (number, customer_id, stat) values ('+32485386902', '1', '1') END"
This throws error:
[Err] 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 sms SET stat = '1' ELSE INSERT INTO sms (number, customer_id, stat) value at line 1
However if I change the update and insert into to 1 and 2 it shows 1 if exist, or 2 if not.
Can anyone help me out :) ? Thanks a lot!
adding a second key to the customer_id made this working:
$sqlsms = "INSERT INTO sms (number, customer_id, stat) VALUES('$phone', '$compID', '$smsPromo') ON DUPLICATE KEY UPDATE stat = '$smsPromo'";
In SELECT query you always must have clause FROM. I recommend you first write a SELECT query to know if the record exists, then if the record not exists you can run INSERT else UPDATE. You can't use SELECT * FROM sms in subquerys, it's mistake sixtaxe.
Related
I have one table which stores some records as JSON. I'm trying to increment the numeric value of a key from JSON column. Below is the query I'm executing in Laravel using DB facade.
DB::connection()
->select("
SELECT CAST(JSON_EXTRACT(consumed, '$.max_users') AS INT) INTO #tmp
FROM subscriptions
WHERE `id` = '2';
UPDATE subscriptions
SET consumed = JSON_SET(consumed, '$.max_users', #tmp+1)
WHERE `id` = '2';
");
It works perfectly ok in PhpMyAdmin however when attempting to execute it from Laravel it throws an exception, that SQL syntax is incorrect (where is it incorrect?).
SQLSTATE[42000]: Syntax error or access violation: 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 'UPDATE subscriptions SET consumed = JSON_SET(consumed, '$.max_users', ' at line 5 (SQL: SELECT CAST(JSON_EXTRACT(consumed, '$.max_users') AS INT) INTO #tmp FROM subscriptions WHEREid= '2'; UPDATE subscriptions SET consumed = JSON_SET(consumed, '$.max_users', #tmp+1) WHEREid= '2'; )
My suspicion is select() does not allow two different queries to be ran at once. However in this particular case I need them so in order to make use of #tmp variable. I could retrieve the value of first query and pass it to the second one using PHP, but for the sake of argument, how to run two DB selects at once in Laravel? 🤔
You can use a single update query to increment this value:
UPDATE subscriptions
SET consumed = JSON_SET(consumed, '$.max_users', CAST(JSON_EXTRACT(consumed, '$.max_users') AS INT) + 1)
WHERE `id` = '2';
I would like to show total purchase followed by date from purchase table to insert into total_purchase table as in date and buy as well as view
my purchase table structure as below:
id|companyName |purchase|date
1|housedotcom |1300 |2016-1-1
2|homedotcom |1234 |2016-1-1
3|gardendotco |1000 |2016-1-2
4|landotcom |999 |2016-1-2
5|garagedotcom|5400 |2016-1-2
6|homedotcom |2600 |2016-1-2
7|housedotcom |1900 |2016-1-2
my total_purchase table as below
id|date |buy
1|2016-1-1|2534
2|2016-2-2|20890
I tried this into sql
INSERT INTO 'total_purchase'(date,buy) SELECT date, sum(purchase)
*FROM 'purchase' GROUP BY date;
And it showed in mysql result as I expected but when I tried insert new data into purchase table as same companyName with different date in mysql it says duplicate as well as in php coding sql it did not worked and showed this error
Error Processing RequestSQLSTATE[42000]: Syntax error or access violation: 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 'FROM purchaseGROUP BY date'
Any suggestions? Thanks in advance.
remove * from your query to be:
INSERT INTO total_purchase (date,buy) SELECT date, sum(purchase)
FROM purchase GROUP BY date;
For inserting value should be entered by just column by column.In Select you use * that return row more than one remove '*'
INSERT INTO 'total_purchase'(date,buy) SELECT date, sum(purchase)
FROM 'purchase' GROUP BY date;
Hello I am trying to execute a mysql query but getting error which I can't understand. The query I am using is
INSERT INTO summary (oid,tab,cost) VALUES('1','7','40') WHERE NOT EXISTS (SELECT * FROM summary WHERE cusid ='1')
I am using this tutorial as my reference, http://www.techonthenet.com/mysql/exists.php
This is the structure of the summary table
This is the error message
#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 new 'WHERE NOT EXISTS (SELECT * FROM summary WHERE cusid = 1)' at line 1
It is not exits. Change it to exists.
INSERT INTO summary (oid,tab,cost) VALUES('1','7','40') WHERE NOT EXISTS (SELECT * FROM summary WHERE cusid ='1')
^
Also you can't use NOT EXISTS with your above query, you can with a subquery.
I've finally gotten my queries ready to insert into code but now I'm getting an error when running the whole query. I believe it has to do with the drop table function. I originally had them inline and then read that I should remove it and add at the beginning of the query like so:
$query = $this->db->query("DROP TABLE IF EXISTS resultx;");
$query = $this->db->query("DROP TABLE IF EXISTS resulty;");
$query = $this->db->query("
CREATE TEMPORARY TABLE resultx AS
select *, CONCAT(Credit,'_',OrderStat) as consol from (..........
I am creating two temp tables and then joining them in the last query. I am not sure how to put that second DROP temp table back into the full query or if that's even the right way to go.
The error that I'm getting is:
A Database Error Occurred
Error Number: 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 'CREATE TEMPORARY TABLE resulty AS select packetDeet,Sales,SaleDate, UserID,Lead' at line 15
Query:
CREATE TEMPORARY TABLE resultx AS
select
*,
CONCAT(Credit,'_',OrderStat) as consol
FROM
( select
packetDetailsId, GROUP_CONCAT(Credit) AS Credit,
GROUP_CONCAT(AccountNum) AS AccountNum,
GROUP_CONCAT(OrderStat) AS OrderStat
FROM
( SELECT
pd_extrafields.packetDetailsId,
CASE WHEN
pd_extrafields.ex_title LIKE ('%Credit%')
THEN pd_extrafields.ex_value
ELSE NULL
END as Credit,
CASE WHEN
pd_extrafields.ex_title LIKE ('%Account%')
THEN pd_extrafields.ex_value
ELSE NULL
END as AccountNum,
CASE WHEN
pd_extrafields.ex_title LIKE ('%Existing%')
THEN pd_extrafields.ex_value
ELSE NULL
END as OrderStat
FROM pd_extrafields
) AS myalias
GROUP BY packetDetailsId
)as TempTab;
CREATE TEMPORARY TABLE resulty AS select packetDeet,Sales,SaleDate, .........
Please let me know if this makes sense or I need to update question with more information.
If you are trying to execute both queries in one call to $this->db->query() the problem is probably that your database library does not permit multiple queries.
To see if that is the problem, you should split them up in two separate queries.
I am writing a PHP Code and having problem with conditions of a query. Also if you could tell my how could i accomplish this by using Stored Procedure in Mysql that would be so nice. My task is to run INSERT query if User foreign key don't exist. If User foreign ke is present in the "User_ID" column then update it.But here i can put condition of unique on Column 'User_ID' in database. So no duplicate event will occur from Database.
The following query is showing this 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 'WHEN 23 NOT IN (SELECT User_ID FROM VoiceMail) ELSE UPDATE VoiceMail SET Urg' at line 3
$result=mysql_query("select * from Users",$con);
while($row= mysql_fetch_array($result))
{
$info=getVM($row['Ext'],$ast);
$info[3]=$row['User_ID']; // To insert User_ID from Users table
$query="INSERT INTO VoiceMail (Urgent, New, Old, User_ID)
VALUES ($info[0],$info[1],$info[2],$info[3])
WHEN $info[3] NOT IN (SELECT User_ID FROM VoiceMail)
ELSE UPDATE VoiceMail SET Urgent=$info[0], New=$info[1], Old=$info[2] WHERE User_ID=$info[3]";
if (!mysql_query($query,$con))
{
die('Error: ' . mysql_error());
}
else echo "Database Updated..!";
Is User_Id an unique key? If so, you can use ON DUPLICATED KEY UPDATE
INSERT INTO VoiceMail (Urgent, New, Old, User_ID)
VALUES ($info[0],$info[1],$info[2],$info[3])
ON DUPLICATE KEY UPDATE Urgent=values(Urgent), New=values(New), Old=values(Old)
Just simply query like :
$query="REPLACE INTO VoiceMail (Urgent, New, Old, User_ID)
VALUES ($info[0],$info[1],$info[2],$info[3])";
It will replace values if already exist, insert new if does not exist.
Hopefully it will help