【问题标题】:Using same table in subquery在子查询中使用同一张表
【发布时间】:2020-03-31 13:43:23
【问题描述】:

我无法将下一个 SQL 代码转换为 laravel eloquent:

SELECT t1.template, t1.created_at
FROM sent_emails t1
where created_at = (
    select max(created_at) from sent_emails t2 where t2.template = t1.template
)
group by t1.created_at, t1.template

或:

SELECT t1.template, t1.created_at
FROM sent_emails t1
JOIN 
(
    SELECT Max(created_at) date, template
    FROM   sent_emails 
    GROUP BY template 
) AS t2 
    ON t1.template = t2.template
    AND t1.created_at = t2.date
group by t1.created_at, t1.template

两个查询都返回相同的数据集。在单独的变量中创建子查询不是一种选择,因为我需要从中返回多个值。

如果我使用模型创建表(而不是使用DB::),我也不知道如何设置别名,所以这是我不成功的尝试:

$sent_emails = SentEmail::where('created_at', function($query) {
            SentEmail::where('template', 't1.template')->orderBy('created_at', 'desc');
        })->groupBy('template', 'created_at')->get(['template', 'created_at']);

【问题讨论】:

  • 请发布您目前尝试的查询生成器表达式。
  • 在更接近的地方,你需要做一些类似 $query->where(subquery results here)

标签: laravel eloquent laravel-query-builder


【解决方案1】:

你的查询应该是这样的(我不在电脑前测试,所以可能需要进一步编辑)

$sent_emails = SentEmail::where('created_at', function($query) {
            $query->where('created_at', SentEmail::->whereColumn('column_name', 'table.column_name')->orderBy('created_at', 'desc')->max('created_at'));
        })->groupBy('template', 'created_at')->get(['template', 'created_at']);

【讨论】:

  • table.column_name 是否引用了这个函数之外的表(我应该给那个表起一个别名然后在这里使用它)吗?
  • @niksrb 我正在按照 laravel-news.com/eloquent-subquery-enhancements 的示例在 where 函数中使用表别名
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-11
  • 2019-05-08
  • 1970-01-01
  • 2019-04-29
  • 2018-09-07
  • 1970-01-01
相关资源
最近更新 更多