简体   繁体   English

在Laravel中创建子查询-查询构建器

[英]Create subquery in Laravel - Query builder

I try to create a sub query. 我尝试创建一个子查询。 For now, my two queries are : 现在,我的两个查询是:

select `key` from messages group by `key`;

and

select * from messages where `key` = 'KEY_RECUP_AU_DESSUS' order by created_at DESC LIMIT 1;

The aim is to highlight my table messages all elements grouped by key and keeping the last element ( created_at desc) 目的是突出显示表messages按键分组的所有元素,并保留最后一个元素(created_at desc)

Thank you 谢谢

Something like this should work: 这样的事情应该起作用:

$data = DB::table('messages')->whereIn('key',function($q) {
    $q->select('key')->from('messages')->groupBy('key');
})->latest()->take(1)->get();

You can do this with two different ways. 您可以使用两种不同的方法来完成此操作。

Query Builder: 查询生成器:

DB::table('messages AS a')
->leftJoin('messages AS b', function($join) {
    $join->on('a.created_at', '<', 'b.created_at');
    $join->on('a.key', '=', 'b.key');
})
->groupBy(['a.key', 'a.message', 'a.created_at'])
->havingRaw('COUNT(b.key) < 1')
->select(['a.key', 'a.message', 'a.created_at'])
->get();

Another way with PARTITION BY PARTITION BY的另一种方式

SELECT 
      key,
      message,
      created_at
FROM (
    SELECT 
          key, 
          message, 
          created_at, 
          rank() OVER (PARTITION BY key ORDER BY created_at DESC) AS rank 
    FROM 
          messages
) AS foo WHERE foo.rank = 1;

if we assume you have table like this. 如果我们假设您有这样的表。

postgres=# select * from messages;
 id |   key   |        message         |         created_at
----+---------+------------------------+----------------------------
  1 | contact | send from contact page | 2015-10-31 19:45:16.850698
  2 | contact | contact page message   | 2015-10-31 19:45:34.417231
  3 | product | product 1              | 2015-10-31 19:45:44.49584
  4 | product | product 2              | 2015-10-31 19:45:46.856691
  5 | contact | hello it is me         | 2015-10-31 18:45:35.801967
  6 | about   | who are you            | 2015-10-31 19:46:04.123369
  7 | product | product 3              | 2015-10-31 19:46:12.414364
  8 | about   | hi guys                | 2015-10-31 19:46:18.23442
(8 rows)

The result will be like this with two different query 结果将是这样,带有两个不同的查询

postgres=# select key, message, created_at from (select key, message, created_at, rank() over (partition by key order by created_at desc) as rank from messages) foo where rank = 1;
   key   |       message        |         created_at         
---------+----------------------+----------------------------
 about   | hi guys              | 2015-10-31 19:46:18.23442  
 contact | contact page message | 2015-10-31 19:45:34.417231 
 product | product 3            | 2015-10-31 19:46:12.414364 
(3 rows)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM