Can I check condition, then insert value to table in SQL - mysql

I am beginner. So I don't know something.
I am trying insert value. But i can't. So i need your help.
My code:
INSERT INTO company_user (stamp_img) values ('test.png') SELECT * FROM company_user WHERE company_register = '123456789';
But Select,
syntax error: select is not valid input at this position.
How to check condition.
I want to check register is true then insert value.
So when i write
`INSERT INTO company_user (stamp_img) values ('test.png')`
Error Code: 1062. Duplicate entry '' for key 'company_register_UNIQUE'
What should I do?
Table Structure
1:

You are probably looking for updating the table. So you should use the UPDATE statement:
UPDATE company_user SET stamp_img = 'test.png' WHERE company_register = '123456789';
This will modifiy the row in your table where company_register is 123456789 setting the stamp_img to test.png.
Is this what you are looking for?

In addition to #Lelio
Are you trying to INSERT data first and then wanted to check if data is inserted or not?
Run following queries directly on query window and see if that you are looking for.
INSERT INTO `company_user` ('stamp_img') values ('test.png');
If its a UNIQUE key constraint check INSERT by changing stamp_img value to something else like test123.png etc.. if by changing the content your query works then you have to update the constraint that suits to your requirements
SELECT * FROM company_user WHERE company_register = '123456789';

This Insert is successful only if there is a record in company_user with company_register as '123456789'
INSERT INTO company_user (stamp_img) (SELECT 'test.png' FROM company_user WHERE company_register = '123456789');

Related

how to insert values in table2 with reference of table 1

I am trying to write a query to insert values in table2 with reference to table1 using a foreign key.table2 columns are (quesid(primary key/auto-increment), ques,ques_desc). There is another table table1 its primary key is foreign key which is also AUTO INCREMENT. So using that i was trying to insert values.
I have written below query:
insert into users_ques values("What is JAVA","Please SHare the details")
from users WHERE quesid = 1;
mysql is giving me error at WHERE (where is not valid at this position).
please help me so that i can sucessfully write this query.
The correct way to use select for insert
insert into users_ques (column1,column2)
select column1,column2
from users
where quesid = 1;
That is not a valid MySQL INSERT syntax. You either do:
INSERT INTO users_ques
VALUES ("What is JAVA","Please SHare the details");
OR
INSERT INTO users_ques
SELECT "What is JAVA","Please SHare the details" FROM users WHERE quesid = 1;
The way you're doing it now is just combining the two method together.
Demo fiddle

skipping duplicate values in mysql while inserting to a target table

Hi i am trying to insert data into another table and i would like to skip duplicate record in the target table. I have used the following mysql query.
insert into adggtnz.`reg02_maininfo`(farmermobile,farmername,farmergender,origin)
select * from (SELECT mobile_no,name,sex,'EADD' FROM EADD.farmer)
as tmp where not exists (select farmermobile from adggeth.`reg02_maininfo` where farmermobile = tmp.mobile_no)
The problem is that when there is a duplicate the query does not completely run how can i avoid the following error
16:09:03 insert into adggtnz.`reg02_maininfo`(farmermobile,farmername,farmergender,origin) select * from (SELECT mobile_no,name,sex,'EADD' FROM EADD.farmer) as tmp where not exists (select farmermobile from adggeth.`reg02_maininfo` where farmermobile = tmp.mobile_no) Error Code: 1062. Duplicate entry '0724961552' for key 'PRIMARY' 0.828 sec
Please help me modify my query
If you want to avoid duplicate entries, you never EVER query first to see if a record exists. You place a unique constraint and use INSERT IGNORE or INSERT INTO ... ON DUPLICATE KEY UPDATE.
The problem with first approach is that you can (and will) get false positives.
In your particular case, the fix is quite easy. You need to add IGNORE after INSERT. That will skip the record if duplicate and continue onto the next one.
INSERT IGNORE INTO adggtnz.`reg02_maininfo`(farmermobile,farmername,farmergender,origin)
SELECT mobile_no, name, sex, 'EADD' FROM EADD.farmer
Get the select query which initially checks the farmer mobile number in reg02_maininfo and then insert into reg02_maininfo.
insert into adggtnz.`reg02_maininfo`(farmermobile,farmername,farmergender,origin)
SELECT mobile_no,name,sex,'EADD' FROM EADD.farmer where mobile_no not in
(select farmermobile from adggeth.`reg02_maininfo`)

SQL Error when trying to insert one value into one row for a column

I'm using MySQL 5.7 and for some reason my INSERT statement isn't working as before even though the syntax looks correct. It's error-ing out on the where statement...
SQL:
insert into users(age) values('16') where username='r';
If the row for username r already exists perhaps you are looking to update the age value instead?
Use: update users set age = 16 where username = 'r' instead.
Also, I'm just guessing here, but maybe age holds a numeric value, and if so you can remove the quotes around 16.
That syntax isn't correct. You can't use where like that. Perhaps you want something like:
insert into users (username, age)
values ('r', '16')
http://dev.mysql.com/doc/refman/5.7/en/insert.html
Alternatively if that user already exists, you might be looking for an update statement instead:
update users set age = '16' where username = 'r'
INSERT statements must not contain a WHERE clause. Remove it.
If, in fact what you are trying to do is update an existing row, use an UPDATE statement, not an INSERT statement.
update users set age = '16' where username='r';
If you want to insert new records in your table, you have to write query for inserting data.
SQL INSERT INTO Statement syntax is this:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
In your case, if you don't have the record in your database, your query will look like this:
INSERT INTO users (username, age)
VALUES ('r', '16')
But if you want to update existing records in your table, you have to write query for updating data using the SQL UPDATE Statement.
The syntax for this is:
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
To update the record/s, you have to specify clause in WHERE which record should be modified.
To modify age of user/s with username that is equals 'r', this is the query:
UPDATE users SET age = 16 WHERE username = 'r'
but if you want to modify for all users which usernames starts with 'r':
UPDATE users SET age = 16 WHERE username = 'r%'
I hope this explanation will help you to understand better SQL statements for INSERT new and UPDATE existing records.

Some problems with INSERT INTO statement

I have this mysql syntax:
INSERT INTO `utilizatori`(
utilizator
)
SELECT
'Mama'
FROM
`utilizatori`
WHERE
NOT EXISTS (SELECT `utilizator` FROM `utilizatori` WHERE utilizator='Mama')
utilizatori is a table, utilizator is a column, Mama is a value
This syntax will insert a value in table only if it doesnt exist.If the value exist it wont create it,so until now it works fine,but if there is no 'Mama' value,then it will insert it...the only problem is that it will insert it multiple times.For example if i have 4 rows,it will insert 'Mama' value 4 times,creating 4 rows.Any idea??
I would make the task easier, clearer by making utilizator field unique.
That way when you add new rows with existing value 'Mama' for utilizator in this case: mysql returns error with the code: 1062, and don't let user have multiple rows with Mama in the table.
So when you run query:
INSERT INTO `utilizatori` (utilizator) VALUES ('Mama')
You can check if MySQL returns any error, but better to check number of affected rows, if insert was successful it will be equal to 1 otherwise 0.
Checking mechanism depends what language and driver you use for connecting to database.
Since you had PHP tag selected you may be using PDO than
$statement->rowCount(); // $statement = PDOStatement, I assume you know this thing well
will give you desired result
Final simple example:
...
if ($statement->rowCount())
{
echo "Cool! You have been added to database";
}
else
{
echo "Hmms! Are you trying to duplicate something?";
}
Try to use group by :
INSERT INTO `utilizatori`(
utilizator
)
SELECT
'Mama'
FROM
`utilizatori`
WHERE
NOT EXISTS (SELECT `utilizator` FROM `utilizatori` WHERE utilizator='Mama')
group by utilizator
You are basically doing:
SELECT ... WHERE NOT EXISTS
...and inserting this in your table. As stated in the comments, just make your utilizator field unique and drop the whole SELECT part from your query.
Where Column is missing...
INSERT INTO `utilizatori`(
utilizator
)
SELECT
'Mama'
FROM
`utilizatori`
WHERE
'Mama'
NOT EXISTS (SELECT `utilizator` FROM `utilizatori` WHERE utilizator='Mama')

Is there a way to use ON DUPLICATE KEY to Update all that I wanted to insert?

I know that you can use ON DUPLICATE KEY UPDATE to update a certain value if there is a record for that key already,
I can do this:
INSERT INTO `tableName` (`a`,`b`,`c`) VALUES (1, 2, 3)
ON DUPLICATE KEY UPDATE `a`=1, `b`=2, `c`=3
But how can I do this without having to write out the columns and values twice?
Unfortunately not.
You can get half-way there by not having to repeat the value:
INSERT INTO `tableName` (`a`,`b`,`c`) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE `a`=VALUES(`a`), `b`=VALUES(`b`), `c`=VALUES(`c`);
But you still have to list the columns.
use REPLACE INTO
The meaning of REPLACE INTO is that IF the new record presents new key values, then it will be inserted as anew record.
IF the new record has key values that match a pre-existing record,then the key violation will be ignored and the new record will replace the pre-existing record.
If it is useful, I made a query to avoid writing by hand the last part of the "on duplicate" query, for versions >= 5.0:
SELECT GROUP_CONCAT( CONCAT(COLUMN_NAME,"=values(", COLUMN_NAME,")") SEPARATOR ", ") FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'database_name' AND TABLE_NAME = 'table_name';
and its output is this:
a=values(a), b=values(b), c=values(c), d=values(d)
on a table that has columns a,b,c and d, so you can append to the first part of the query:
INSERT INTO `tableName` (`a`,`b`,`c`, `d`) VALUES (1,2,3,4) ON DUPLICATE KEY UPDATE a=values(a), b=values(b), c=values(c), d=values(d)
UPDATE:
For a very long list of columns you may see a truncated output, you may use this statement before the query above (thanks Uncle iroh):
SET SESSION group_concat_max_len = 1000000;
per #BhendiGawaar's comment on #Lightness Races in Orbit's answer, here is the MySQL 8.019+ version:
INSERT INTO t1 (a,b,c) VALUES (1,2,3),(4,5,6) AS new
ON DUPLICATE KEY UPDATE c = new.a+new.b;
OR
INSERT INTO t1 (a,b,c) VALUES (1,2,3),(4,5,6) AS new(m,n,p)
ON DUPLICATE KEY UPDATE c = m+n;
Works with set as well:
INSERT INTO t1 SET a=1,b=2,c=3 AS new
ON DUPLICATE KEY UPDATE c = new.a+new.b;
INSERT INTO t1 SET a=1,b=2,c=3 AS new(m,n,p)
ON DUPLICATE KEY UPDATE c = m+n;
Copied directly from MySQL Docs
The deprecation warning about the use of VALUES:
The use of VALUES() to refer to the new row and columns is deprecated beginning with MySQL 8.0.20, and is subject to removal in a future version of MySQL. Instead, use row and column aliases, as described in the next few paragraphs of this section.
i know this is an old question, and this is a somewhat unconventional answer, but i ran into the same thing and was having issues with setting the group_concat_max_len property mentioned in another answer and was always getting a truncated result. Another option that I ultimately went with when writing a long script was to use this formula in excel:
=SUBSTITUTE(TRIM(A1), ",", "") & " = VALUES(" & SUBSTITUTE(TRIM(A1), ",", "") & "),"
where A1 is the cell you copy the field name into. To do this quickly, I'd right click the table and copy the select statement to the clipboard, which gives you all the colum names, the formula removes the commas.
Hope this helps someone!