【问题标题】:Complex select from 3 columns in MySQL从 MySQL 中的 3 列中进行复杂选择
【发布时间】:2012-08-27 13:25:37
【问题描述】:

我在 MySQL 数据库中有 3 个表。

表 1(比如说它叫做client)有一个客户的信息:client_id and client_name 表 2(比如称为 user_to_client)包含与我系统用户的每个客户端相关的信息:user_id, client_id and order_flag

在这个表中clients和users是重复的,order flag表示用户和client有未完成的业务。 user_id 和 client_id 的组合在该表中只能找到一次,这意味着用户 5 和客户端 3 只注册了一次。

表 3(称为orders)保存有关订单基本信息的信息:client_id, user_id, order_id。它保留了两个不同的日期类型列:date_started 保存开始构建订单的日期信息,date_sent 保存订单发送到操作区域的日期。

我在两个表中重复信息的原因是因为在表 3 中,用户和客户可能有大量未完成的订单不再可用,但我需要保留公司记录。

所以,我需要做的是选择最后 4 个未完成订单的客户而不重复客户,以及最后一个未完成订单的 ID。基本上我需要从表 1 中选择客户端名称,如果该客户端在表 2 中激活了 order_flag(值 1),并且从表 3 中选择了属于该用户的最新 order_id。

我无法修改这些表,因为它们已经被用于另一项工作,那么,有人可以帮助我使用 MySQL 查询来完成这项工作吗?

【问题讨论】:

  • 而不是这个定义一个示例表结构,以便它给出更清晰的画面..否则使用 sqlfiddle .com 来设计你的表

标签: mysql select inner-join


【解决方案1】:

以下查询不查询回答您的问题,因为客户可以重复。但是,它为弄清楚该做什么提供了一个很好的基础:

select c.*, o.*
from client c join
     user_to_client uc
     on c.client_id = uc.client_id join
     orders o
     on o.client_id = uc.client_id and
        o.user_id = uc.user_id
where uc.order_flag = 1 and
      o.date_sent is null  -- does this make an order "unfinished"?
order by date_started desc
limit 4

我不确定您如何找到“未完成”的订单。所以,我猜它是基于 date_sent 为 NULL。

您实际需要的要复杂一些。您需要每个客户最近的“未完成”订单。以下查询使用相关子查询来获取此信息:

select client_id, maxdate,
       (select max(order_id)
        from orders o
        where o.client_id = c.client_id and o.date_sent is null and o.date_started = c.maxdate) as orderid
from (select c.client_id, MAX(date_started) as maxdate
      from client c join
           user_to_client uc
           on c.client_id = uc.client_id join
           orders o
           on o.client_id = uc.client_id and
              o.user_id = uc.user_id
      where uc.order_flag = 1 and
            o.date_sent is null
      group by c.client_id
      order by 2 desc
      limit 4
     ) c

这假设它可以根据客户 ID 和日期找到正确的订单。如果不是这样,则相关子查询必须引入其他表才能获得正确的过滤信息。

【讨论】:

  • 感谢您的帮助。它实际上给了我一个想法,因为我很着急,使用了 2 个查询...第一个选择标记为挂单的客户,然后在订单数据库中搜索 MAX(date_started),其中 date_sent null user_id in(list of ids )
猜你喜欢
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-16
  • 2017-03-16
  • 2017-04-13
  • 1970-01-01
相关资源
最近更新 更多