简体   繁体   English

如何基于一个列将列添加到另一张表?

[英]How to add columns to another table based on one column?

I have my shop database and I want to join two tables together. 我有我的商店数据库,我想将两个表连接在一起。

id_order | reference | id_shop_group | id_shop | id_carrier | id_lang | id_customer | id_cart

This the header row of my orders table and below is the header of customers table. 这是我的orders表的标题行,下面是customers表的标题。

id_customer | id_shop_group | id_shop | id_gender | firstname | lastname 

What I want to do is to join them based on id_customer column. 我想做的是基于id_customer列加入他们。 More specifically I want to add all columns of customers except the ones that are already there to orders table based on id_customer . 更具体地说,我想将除已存在的customers以外的所有customers列添加到基于id_customer orders表中。 After joining the tables should look like this: 加入表后应如下所示:

id_order|reference|id_shop_group|id_shop|id_carrier|id_lang|id_customer|id_cart|id_gender|firstname|lastname 

When searching for a solution I found INNER JOIN keyword, but I'm not sure how to use it the way I want. 在寻找解决方案时,我发现了INNER JOIN关键字,但是我不确定如何以所需的方式使用它。

We don't "Add columns to a table". 我们不“将列添加到表中”。 We, instead, submit SQL to the database that returns the result set that we want. 相反,我们将SQL提交到返回所需结果集的数据库。 In your case we want to Join the two tables and we can do that using an INNER JOIN on your id_customer field that is common between the two tables. 在您的情况下,我们希望联接两个表,我们可以在两个表之间通用的id_customer字段上使用INNER JOIN进行id_customer We can turn that into it's own table if you want to hold, permanently, those results. 如果您想永久保留这些结果,我们可以将其变成它自己的表。 It would look something like 看起来像

SELECT 
    orders.id_order,
    orders.reference,
    orders.id_shop_group,
    orders.id_shop,
    orders.id_carrier,
    orders.id_lang,
    orders.id_customer,
    orders.id_cart,
    customer.id_gender,
    customer.firstname,
    customer.lastname
FROM orders INNER JOIN customer on orders.id_customer = customer.id_customer;

You can tweak the list of fields to be returned from the joining of these tables to suit your needs. 您可以调整从这些表的联接中返回的字段列表,以满足您的需求。

The fact that id_shop and id_shop_group are in both tables suggests they are part of a composite key. 两个表中都存在id_shop和id_shop_group的事实表明它们是组合键的一部分。 You may need to join using all three shared columns to guarantee unique rows. 您可能需要使用所有三个共享列进行连接以保证唯一的行。 Otherwise you may retrieve duplicate order rows where the customer belongs to more than one shop. 否则,您可能会检索客户属于多个商店的重复订单行。

eg 例如

SELECT
...
FROM orders INNER JOIN customer on orders.id_customer = customer.id_customer 
and orders.id_shop_group = customer.id_shop_group
and orders.id_shop = customer.id_shop

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

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