我有三个表Order,Customer,Address。

编辑:

我想获取在网站上注册的所有客户。
如果客户下了任何订单,我想从订单列表中获取最新订单,
如果客户未下任何订单,那么我想将该字段设置为空白,如下表所示

For eg :

       Customer_Name   Email ID   Country   Phone   Latest_Order_Code
       A               xxxx        xxxx     x       1234

       B               yyyy        yyyy     y

       C               ffff        tttt     l       3456

       D               zzzz        iiii     o

任何帮助,将不胜感激?

最佳答案

请参阅下面的查询,其中我仅获取订单代码和客户名称。您可以编写更多的联接并根据需要选择字段。

select {o.code} as orderCode,
       {c.name} as name,
       {a.cellphone} as cellphone

from   {order as o
        join Customer as c on {c.pk} = {o.user}
        join Address as a on {o.deliveryaddress} = {a.pk}
       }

       where {o.code} in ({{select max({code}) from {order} group by {user}}})

更新:获取所有注册客户及其最近的订单信息
select t1.name, t2.orderCode, t2.cellphone

from

({{
  select {pk} as userPk, {name} as name from {Customer}
}}) as t1

LEFT JOIN

({{
    select
       {o.code} as orderCode,
       {o.user} as user,
       {a.cellphone} as cellphone

from   {order as o
        join Address as a on {o.deliveryaddress} = {a.pk}
       }

       where {o.code} in ({{select max({code}) from {order} group by {user}}})
}}) as t2

on t2.user = t1.userPk

详细信息how to write complex flexible search query join using the dynamic tables?

10-07 13:58