【问题标题】:MySQL Query tableA order by if has post in tableB with date of this monthMySQL Query table order by if has post in table with this month
【发布时间】:2012-09-10 15:03:50
【问题描述】:

我有两张桌子。

我想查询tableA并按tableB排序。

这是一个会计系统。

TableA 包含客户。表 B 包含客户支付的款项。

我想 select * 从 TableA 订购,他在 TableB 中的付款首先是本月的日期,然后是没有付款的其余部分。

【问题讨论】:

  • 您可以在 ORDER BY 子句中使用函数和表达式,例如 ORDER BY IF(b.payment = now(), 0, 1)。如需更多帮助,请显示示例数据和所需结果。

标签: mysql join


【解决方案1】:
SELECT
    *
FROM TableA
LEFT JOIN TableB
    ON TableB.customer_id = TableA.customer_id
ORDER BY COALESCE(TableB.payDate, '1900-01-01') DESC

【讨论】:

  • 可能不是 OP 想要的,因为这将为过去付款超过 1 次的客户返回多行。
【解决方案2】:

您可以将两个表外连接,在表A中按标识信息分组,在表B中按最大付款日期排序,如下所示:

select customer.customer_id, customer.first_name, customer.last_name, 
  max(payment.payment_date)
from customer
  left outer join payment on payment.customer_id = customer.customer_id
group by customer.customer_id, customer.first_name, customer.last_name
order by max(payment.payment_date) desc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 2011-12-29
    • 2021-11-10
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多