I'm trying to do a INSERT SELECT with condition but smthg seems to be wrong. I get an 1064 error for wrong syntax.
Here is the query :
INSERT INTO `db1`.`table`.`field` (
SELECT a.`field1` , a.`field2`
FROM `db2`.`table1` a, `db2`.`table2` b
WHERE a.`field1` = b.`field1`
AND b.`field2` = 'value'
)
WHERE a.`field1` = `db1`.`table1`.`field1`
Thank in advance for any suggestions
Syntax for the insert select is :
INSERT california_authors (au_id, au_lname, au_fname)
SELECT au_id, au_lname, au_fname
FROM authors
WHERE State = 'CA'
so in you case it like
INSERT INTO `db1`.`table` (.... field list ...)
select
... col for select .....
from table
where ... where condition ....
The syntax for INSERT INTO is usually
INSERT INTO myTable (field1,field2,...,fieldN)
SELECT field1,field2,etc FROM myTable WHERE condition
You need to simplify your queries and think through what you're trying to do.
My question was bad. In this case it is not Insert but an Update query which is needed
Related
I wanted to insert a values into a declared variable.
This is how it is so far :
INSERT INTO DP_Transaction(Trans_Reference, Trans_Action, Trans_Name,
Trans_Date, Trans_Comment)
VALUES(#formId, 'Cancelled by', 'Workflow Manager', '2021-03-29 09:52:28.257', 'test')
And the values I want to add inside #formid is something like below:
'12323985',
'39864345',
'89426596',
'97070302',
'56746838'
And my expected result is all the values inside the statement will be insert into these #formId rows:
'12323985',
'39864345',
'89426596',
'97070302',
'56746838'
Can anyone help?
You could place the form ID values into a subquery and then rephrase the insert as an INSERT INTO ... SELECT:
INSERT INTO DP_Transaction (Trans_Reference, Trans_Action,
Trans_Name, Trans_Date, Trans_Comment)
SELECT
formid,
'Cancelled by',
'Workflow Manager',
'2021-03-29 09:52:28.257',
'test'
FROM
(
SELECT '12323985' AS formid UNION ALL
SELECT '39864345' UNION ALL
SELECT '89426596' UNION ALL
SELECT '97070302' UNION ALL
SELECT '56746838'
) t;
If you were using a different database, e.g. SQL Server, then you could have used APPLY along with a string splitting function. But this is not an option in MySQL to my knowledge.
This must be fairly straight forward, as I tend to use ORMs I don't have to get my hands dirty often and am therefore struggling!
I have a database and want to get several fields from a table, that bit is easy..
SELECT main_table.registration_number, main_table.registered_name FROM main_table;
I want to filter the results based on another table, which is also easy..
SELECT second_table.registration_number FROM second_table WHERE this_field = '' AND that_field = '0';
Now the problem is I want to run the first query based on the second queries result set, I was thinking something like this:
SELECT main_table.registration_number, main_table.registered_name FROM main_table WHERE main_table.registration_number IN (SELECT * FROM second_table WHERE this_field = '' AND that_field = '0');
This gives me: Error Code: 1241. Operand should contain 1 column(s)
Am I handling this completely wrong?
Your subquery should do something like below,
(select * from table) in subquery is not what you really need to do your
so the subquery should return one column
(SELECT registration_number FROM second_table WHERE this_field = '' AND that_field = '0');
You cannot have multiple columns being returned in a subquery like
that, doing so it will result in such error
You have to select a column
SELECT main_table.registration_number, main_table.registered_name FROM
main_table WHERE main_table.registration_number IN (SELECT
registration_number FROM second_table WHERE this_field = '' AND
that_field = '0');
I'm trying to insert the JobNo and CellNo columns that are not in Table_1 from View_1. I wrote this query & I get an error.
Please help me out in correcting this.
I'm using SQL Server 2008
INSERT INTO Table_1(ID, JobNo, CellNo)
SELECT View_1.ID, View_1.JobNo, View_1.CellNo
FROM View_1
WHERE View_1.JobNo
AND View_1.CellNo NOT IN (SELECT JobNo, CellNo FROM Table_1)
The issue is your WHERE clause - you can't compare sets of fields like this. You can only compare a single field at a time.
Try instead:
WHERE View_1.JobNo NOT IN(SELECT JobNo FROM Table_1)
AND View_1.CellNo NOT IN (SELECT CellNo FROM Table_1)
Alternatively you can use a single EXISTS statement:
INSERT INTO Table_1(ID, JobNo, CellNo)
SELECT View_1.ID, View_1.JobNo, View_1.CellNo
FROM View_1 v
WHERE NOT EXISTS (SELECT 1 FROM Table_1 t
WHERE t.JobNo = v.JobNo
AND t.CellNo = v.CellNo)
Since you're using SQL Server 2008, you can make use of the MERGE statement:
MERGE INTO Table_1 dst
USING (
SELECT View_1.ID, View_1.JobNo, View_1.CellNo
FROM View_1
) src
ON src.JobNo = dst.JobNo
AND src.CellNo = dst.CellNo
WHEN NOT MACHED THEN INSERT (ID, JobNo, CellNo)
VALUES (src.ID, src.JobNo, src.CellNo)
I personally find a MERGE statement more concise than INSERT .. SELECT .. WHERE.
I am trying to use an IF statement in a MySQL select query.
I am getting an error after the AND statement where the first IF.
SELECT J.JOB_ID,E.COMPANY_NAME,J.JOB_DESC,JT.JOBTYPE_NAME,J.COMPENSATION,ST.STATE_NAME,MC.METRO_CITY_NAME,I.INDUSTRY_NAME,
J.JOB_CONTACT_PERSON,J.DT_INSRT,J.JOB_TITLE,J.JOB_EXP_DATE,J.SKILLS
FROM JOBS J
JOIN EMPLOYER E ON J.COMPANY_ID=E.COMPANY_ID
JOIN LOOKUP_JOBTYPE JT ON J.JOB_TYPE=JT.JOBTYPE_ID
JOIN LOOKUP_STATE ST ON J.STATE_ID=ST.STATE_ID
JOIN JOBS_LOCATION JL ON J.JOB_ID=JL.JOB_ID
JOIN LOOKUP_METRO_CITY MC ON JL.METRO_CITY_ID=MC.METRO_CITY_ID
JOIN LOOKUP_INDUSTRY I ON J.INDUSTRY_ID=I.INDUSTRY_ID
JOIN JOBS_QUALIFICATION JQ ON J.JOB_ID=JQ.JOB_ID
JOIN LOOKUP_DEGREE_QUALIFICATION LDQ ON LDQ.QUALIFICATION_ID = JQ.QUALIFICATION_ID
WHERE J.ACTIVE='Y' AND J.DT_INSRT > COALESCE(pEmailSntDt,DATE_SUB(SYSDATE(),INTERVAL 4 DAY))
AND
IF(JQ.COURSE_ID=0)
THEN
IF(JQ.DEGREE_ID=0)
THEN J.SKILLS LIKE CONCAT('%', pSkills,'%')
ELSE
JQ.DEGREE_ID=pDegreeId OR J.SKILLS LIKE CONCAT('%', pSkills,'%')
END IF
ELSE
JQ.COURSE_ID=pCourseId OR IF(JQ.DEGREE_ID=0)
THEN
J.SKILLS LIKE CONCAT('%', pSkills,'%')
ELSE
JQ.DEGREE_ID=pDegreeId OR J.SKILLS LIKE CONCAT('%', pSkills,'%')
END IF
END IF
GROUP BY J.JOB_ID ORDER BY J.DT_INSRT DESC;
Why doesn't this work and what is the proper way to do an IF statement in a MySQL query?
The IF/THEN/ELSE construct you are using is only valid in stored procedures and functions. Your query will need to be restructured because you can't use the IF() function to control the flow of the WHERE clause like this.
The IF() function that can be used in queries is primarily meant to be used in the SELECT portion of the query for selecting different data based on certain conditions, not so much to be used in the WHERE portion of the query:
SELECT IF(JQ.COURSE_ID=0, 'Some Result If True', 'Some Result If False'), OTHER_COLUMNS
FROM ...
WHERE ...
How to use an IF statement in the MySQL "select list":
select if (1>2, 2, 3); //returns 3
select if(1<2,'yes','no'); //returns yes
SELECT IF(STRCMP('test','test1'),'no','yes'); //returns no
How to use an IF statement in the MySQL where clause search condition list:
create table penguins (id int primary key auto_increment, name varchar(100))
insert into penguins (name) values ('rico')
insert into penguins (name) values ('kowalski')
insert into penguins (name) values ('skipper')
select * from penguins where 3 = id
-->3 skipper
select * from penguins where (if (true, 2, 3)) = id
-->2 kowalski
How to use an IF statement in the MySQL "having clause search conditions":
select * from penguins
where 1=1
having (if (true, 2, 3)) = id
-->1 rico
Use an IF statement with a column used in the select list to make a decision:
select (if (id = 2, -1, 1)) item
from penguins
where 1=1
--> 1
--> -1
--> 1
If statements embedded in SQL queries is a bad "code smell". Bad code has high "WTF's per minute" during code review. This is one of those things. If I see this in production with your name on it, I'm going to automatically not like you.
try this code worked for me
SELECT user_display_image AS user_image,
user_display_name AS user_name,
invitee_phone,
(CASE WHEN invitee_status = 1 THEN "attending"
WHEN invitee_status = 2 THEN "unsure"
WHEN invitee_status = 3 THEN "declined"
WHEN invitee_status = 0 THEN "notreviwed"
END) AS invitee_status
FROM your_table
Here are two statements that I'd like to work, but which return error messages:
IF EXISTS (SELECT * FROM gdata_calendars WHERE `group` = ? AND id = ?) SELECT 1 ELSE SELECT 0
and
IF ((SELECT COUNT(*) FROM gdata_calendars WHERE `group` = ? AND id = ?) > 0) SELECT 1 ELSE SELECT 0;
The question marks are there because I use parametrized, prepared, statements with PHP's PDO. However, I have also tried executing this with data manually, and it really does not work.
While I'd like to know why each of them doesn't work, I would prefer to use the first query if it can be made to work.
You cannot use IF control block OUTSIDE of functions. So that affects both of your queries.
Turn the EXISTS clause into a subquery instead within an IF function
SELECT IF( EXISTS(
SELECT *
FROM gdata_calendars
WHERE `group` = ? AND id = ?), 1, 0)
In fact, booleans are returned as 1 or 0
SELECT EXISTS(
SELECT *
FROM gdata_calendars
WHERE `group` = ? AND id = ?)
I found the example RichardTheKiwi quite informative.
Just to offer another approach if you're looking for something like IF EXISTS (SELECT 1 ..) THEN ...
-- what I might write in MSSQL
IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='')
BEGIN
SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
INSERT INTO TABLE(FieldValue) VALUES('')
SELECT SCOPE_IDENTITY() AS TableID
END
-- rewritten for MySQL
IF (SELECT 1 = 1 FROM Table WHERE FieldValue='') THEN
BEGIN
SELECT TableID FROM Table WHERE FieldValue='';
END;
ELSE
BEGIN
INSERT INTO Table (FieldValue) VALUES('');
SELECT LAST_INSERT_ID() AS TableID;
END;
END IF;
The accepted answer works well and one can also just use the
If Exists (...) Then ... End If;
syntax in Mysql procedures (if acceptable for circumstance) and it will behave as desired/expected. Here's a link to a more thorough source/description: https://dba.stackexchange.com/questions/99120/if-exists-then-update-else-insert
One problem with the solution by #SnowyR is that it does not really behave like "If Exists" in that the (Select 1 = 1 ...) subquery could return more than one row in some circumstances and so it gives an error. I don't have permissions to respond to that answer directly so I thought I'd mention it here in case it saves someone else the trouble I experienced and so others might know that it is not an equivalent solution to MSSQLServer "if exists"!
If your table has an auto-incrementing primary key, you can use REPLACE INTO ... VALUES
SELECT #id := id FROM tableName WHERE fieldName='criteria value' LIMIT 1;
REPLACE INTO tableName(id, fieldName, col1, col2)
VALUES (#id, 'criteria value', 'value1', 'value2')
If the select statement returns NULL, then a new row is inserted.
Otherwise, if a row is found, it will update the row with key #id.
SELECT IF((
SELECT count(*) FROM gdata_calendars
WHERE `group` = ? AND id = ?)
,1,0);
For Detail explanation you can visit here