Khuma
Khuma

Reputation: 57

How to insert values from other table?

I need to INSERT(not UPDATE) some values from one table to other

That`s how I do:

INSERT INTO `users`(`id`) VALUES(('SELECT `id` FROM `clients` WHERE `phone_number`="+115522225500"))

but that shows an error

how should I correct it

Cheers !

Upvotes: 0

Views: 57

Answers (2)

Samuel Munyili
Samuel Munyili

Reputation: 41

As Elliott Frisch has said, you will need to share the error message. (Only then can anyone know exactly how to help you) But basically I think your query may be having any or all of these possible errors:

  1. You have unnecessary single quotes in the query. Remove all the single quotes and replace the double quotes around the phone number with single quotes
  2. The return value of this part (after of course taking care of (1) above)

('SELECT id FROM clients WHERE phone_number="+115522225500")

may be more than one value if by any possibility the same phone number appears in more than one record, this is assuming that it is not a unique column. You could consider using (SELECT TOP 1 ID from clients....

  1. The select query returns a null yet the column ID in Users does not allow nulls.

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269773

Just use insert . . . select:

INSERT INTO users(id) 
    SELECT id
    FROM clients
    WHERE phone_number = '115522225500';

Note that phone numbers would normally be strings and so the value should have single quotes around it.

Upvotes: 0

Related Questions