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

1.8k views Asked by At

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: enter image description here

3

There are 3 answers

0
Lelio Faieta On BEST ANSWER

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?

0
Mangesh Sathe On

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';
0
Raja vikraman On

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');