Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert into with 2 (multiple) select?

What I am trying to do is something like this :

INSERT INTO LIVRE (id_livre, id_client, id_produit)
VALUES (
  null,
  SELECT id_client from CLIENT where distributeur like "%Traffic%", 
  SELECT id_produit from PRODUIT where num_serie_produit = 1401000
);

Is it possible with 1 SELECT ?

I tried something like :

INSERT INTO LIVRE (id_livre,id_client,id_produit) 
SELECT
  null,
  C.id_client,
  P.id_produit 
FROM
  LIVRE, CLIENT C, PRODUIT P
WHERE
  C.distributeur like "%Traffic%"
  AND P.num_serie_produit = 1401000;

but I dont know how to write it correctly :/

I searched but I couldn't find really what i want. So sorry if someone already asked it.

Thanks.

like image 440
Booba__2012 Avatar asked Dec 09 '25 07:12

Booba__2012


1 Answers

Use something similar to.

 INSERT INTO c (aID, bID) 
 SELECT a.ID, B.ID 
 FROM A, B 
 WHERE A.Name='Nisha'
 AND B.Class='Java';

In your case, it would be: (JUST REMOVE LIVRE FROM WHERE CLAUSE)

INSERT INTO LIVRE (id_livre,id_client,id_produit) 
SELECT null, C.id_client,P.id_produit 
FROM CLIENT C, PRODUIT P
WHERE C.distributeur like "%Traffic%"
    AND P.num_serie_produit = 1401000;

Assuming that there will be only one row returned from select query,If more than 1 row returned by select query, then use rownum or limit function as appropriate to below query.

INSERT INTO LIVRE (id_livre, id_client, id_produit)
VALUES 
(null, 
(SELECT id_client from *CLIENT* where distributeur like "%Traffic%"), 
(SELECT id_produit from *PRODUIT* where num_serie_produit = 1401000) );
like image 197
Nishanthi Grashia Avatar answered Dec 11 '25 02:12

Nishanthi Grashia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!