我尝试从数据库中检索消息组,并且查询没有按created_at
标志对结果进行排序。
查询如下所示:
$groups = self::
where(function($query) use ($user_id) {
$query->where('to_id', $user_id);
$query->orWhere('from_id', $user_id);
})
->join('users as u1', 'user_messages.to_id', 'u1.id')
->join('users as u2', 'user_messages.from_id', 'u2.id')
->select(
'u1.nickname as u1_nickname',
'u1.id as u1_id',
'u2.id as u2_id',
'u2.nickname as u2_nickname',
'user_messages.created_at'
)
->orderBy('created_at', 'desc')
->groupBy(
DB::raw(
'if (user_messages.from_id = '.$user_id.', user_messages.to_id, user_messages.from_id)'
)
)
->get()
->toArray();
$user_id
是经过身份验证的用户。
orderBy子句未按预期工作。用户未按发送邮件的最后一个人分组。
有什么建议吗?谢谢。
答案 0 :(得分:0)
您可以使用SELECT
clients.client_id,
clients.first_name,
COALESCE(SUM(total_charged), 0) AS total_charged
FROM
clients
LEFT JOIN (SELECT
c.client_id,
a.route_property_reg_id,
COALESCE(SUM(ROUND((a.rate_charged * (1 + (tax_types.rate / 100))), 2)), 0) AS total_charged
FROM
route_property_reg a
LEFT JOIN properties ON a.property_id = properties.property_id
LEFT JOIN clients c ON properties.client_id = c.client_id
LEFT JOIN tax_types ON a.tax_rate_charged = tax_types.tax_type_id
WHERE
NOT EXISTS( SELECT
NULL
FROM
invoice_lines b
LEFT JOIN invoices ON b.invoice_id = invoices.invoice_id
LEFT JOIN clients d ON invoices.client_id = d.client_id
WHERE
b.route_property_reg_id = a.route_property_reg_id
AND d.client_id = c.client_id)
GROUP BY client_id) AS charged ON clients.client_id = charged.client_id
GROUP BY clients.client_id
为每封邮件获取最新的Max
。
查询可能像:
created_at