简体   繁体   中英

Loop sql query with insert

I have this select query:

SELECT * FROM `jos_users` 
left join jos_clientes on jos_users.id = jos_clientes.id_user 
where jos_clientes.id_user is null 
and email like '%novousuario%'';

This query returns me all jos_users that have not a row on the jos_clientes table.

The jos_clientes schema is:

create table jos_clientes(
  id int(11) not null auto_increment primary key,
  id_user int(11) not null,
  codigo_cpf_cnpj varchar(20) not null,
  type varchar(4) not null
);

Is there any way to, for each row, I insert a new row in jos_clientes?

foreach jos_users
    INSERT INTO jos_clientes VALUES (null, jos_users.id_user, jos_users.username, IF(length(jos_users.username)>11,'cnpj','cpf'));

How can I do this with sql on mysql?

You can use the INSERT INTO ... SELECT FROM approach:

INSERT INTO jos_clientes (id_user, username, code)
  SELECT jos_users.id_user, jos_users.username, IF(length(jos_users.username)>11,'cnpj','cpf') FROM jos_users

You need to be specific about the fields you're populating though unless the columns match exactly.

Adjust the SELECT sub-statement according to your needs and be sure it produces the kind of results you can insert directly into your jos_clientes table.

Try the following query:

 INSERT INTO jos_clientes SELECT null,d.id_user, d.username,IF(length(d.username)>11,'cnpj','cpf'))
    FROM jos_users d;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM