简体   繁体   English

如何使用来自其他两个表的数据填充 mysql 表

[英]How to populate a mysql table with data from two other tables

I have two tables with a many-to-many relation, and a joint table between them, for example:我有两个具有多对多关系的表,以及它们之间的联合表,例如:

client (id, name)
address (id, address)
client_address (client_id, address_id)

I need to populate the client_address table with a line for every client, using a specific address, like:我需要使用特定地址为每个客户端填充一行 client_address 表,例如:

client_id, address_id
1,         1
2,         1
3,         1
4,         1
etc...

I tried something like this (which obviously does not work):我尝试了这样的事情(显然不起作用):

INSERT INTO 
  client_address (`client_id`, `address_id`) 
  SELECT id from client, 
  SELECT id from address where address = 'My Address';

can I do this with a single query?我可以用一个查询来做到这一点吗?

If you have to populate it manually just like your example you can try to use CROSS JOIN:如果您必须像您的示例一样手动填充它,您可以尝试使用 CROSS JOIN:

INSERT INTO 
  client_address (`client_id`, `address_id`) 
  SELECT c.id, a.id 
  FROM client c, 
  CROSS JOIN address a 
  WHERE address = 'My Address';

This will create a line for every client you have in CLIENT table and the address you chose in the WHERE clause这将为您在 CLIENT 表中的每个客户以及您在 WHERE 子句中选择的地址创建一行

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

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