获取一对多关系数据

时间:2013-08-04 05:50:54

标签: sql

大家好,我有三张桌子。

  1. 客户(客户名单)
  2. 付款(客户付款清单)
  3. 订单(客户订单清单)
  4. 客户可以拥有多个关系中的多个付款和订单。

    我尝试了以下查询,但没有显示正确的结果。

    select a.name, b.job_date as JobDate, c.order_date as OrderDate from Customers a
    inner join Jobs b on a.id = b.customer_id
    inner join Orders c on a.id = c.customer_id
    where a.id = 1;
    

    我需要的是展示客户的订单和工作。

2 个答案:

答案 0 :(得分:0)

尝试左连接而不是内连接。子表可能没有与Customers.id = 1相关的记录。

select a.name, b.job_date as JobDate, c.order_date as OrderDate from Customers a
left join Jobs b on a.id = b.customer_id
left join Orders c on a.id = c.customer_id
where a.id = 1;

答案 1 :(得分:0)

如果您想获得所有订单,可以使用以下内容:

select a.name, c.order_date as OrderDate from Orders c 
inner join Customers a on a.id = c.customer_id
where a.id = 1;

您可以构建类似的查询来获取所有员工的工作:

select a.name, b.job_date as JobDate from Jobs b 
    inner join Customers a on a.id = b.customer_id
    where a.id = 1;