使用三个表的灵活搜索查询

Flexible search query using three tables

我有三个 tables Order,Customer,Address。

已编辑:

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

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 字段。

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

详情posthow to write complex flexible search query join using the dynamic tables?