简体   繁体   English

用插入循环SQL查询

[英]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. 该查询返回所有在jos_clientes表上没有行的jos_users。

The jos_clientes schema is: jos_clientes模式为:

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? 有什么方法可以为每行在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? 如何在mysql上使用sql做到这一点?

You can use the INSERT INTO ... SELECT FROM approach: 您可以使用INSERT INTO ... SELECT FROM方法:

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. 根据需要调整SELECT子语句,并确保它产生可以直接插入到jos_clientes表中的结果类型。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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