【问题标题】:Bringing data attribute over from another table Mysql从另一个表Mysql带来数据属性
【发布时间】:2020-03-25 21:53:00
【问题描述】:

我有这三个没有外键链接的镜头。 (下面的一些示例数据)。

经销商的客户拥有指定的客户编号。但是,另一个经销商可以有一个具有相同号码的客户,但他们不是同一个客户。

|---------------------|    |---------------------|   |---------------------| 
|   DISTINCT_DEALER   |    |  DISTINCT_CUSTOMER  |   |    CUSTOMER_SALES   |
|---------------------|    |---------------------|   |---------------------| 
|      d_id   (pk)    |    |       d_id          |   |        d_id         |
|---------------------|    |---------------------|   |---------------------| 
|    dealer_address   |    |     dealer_name     |   |   customer_number   |
|---------------------|    |---------------------|   |---------------------| 
|    dealer_city      |    |   customer_number   |   |    total_sales      |
|---------------------|    |---------------------|   |---------------------| 
|    dealer_state     |    |    customer_name    |
|---------------------|    |---------------------| 
|    dealer_zip       |    |    customer_email   |
|---------------------|    |---------------------|

样本数据:

解决这个问题的最佳方法是什么?

我现在有这个问题

select cs.d_id, cs.customer_number, cs.total_sales from cs_sales cs where cs.d_id in
(select dc.d_id from dcust dc where dc.d_id = 'A00007');

它完全符合我的需要,除了在表中返回客户姓名,以便我可以匹配每个经销商的客户销售额。想法?

【问题讨论】:

    标签: mysql sql database join foreign-keys


    【解决方案1】:

    尝试将您的子查询放在 from 子句中,然后添加另一个字段,如下所示:

    select cs.d_id, cs.customer_number, cs.total_sales, subquery_dc.customer_name
    from cs_sales cs,
           (select dc.d_id, dc.customer_name from dcust dc 
            where dc.d_id = 'A00007') subquery_dc
     where cs.d_id in subquery_dc.d_id;
    

    这将创建一个具有 d_id 的虚拟表,以及从 dcust 表中提取的 customer_name 字段。然后,您可以像以前一样加入这些特定记录,还可以拉回 customer_name 字段进行显示。

    【讨论】:

    • where cs.d_id in subquery_dc.d_id收到错误
    • @jesus2kus,什么样的错误?可以发在这里吗?
    猜你喜欢
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多