Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

Cara menggunakan GROUP BY dan ORDER BY bersama-sama di LARAVEL 5.6

Gunakan subquery join:

$days = 10 ;
$currencies = Currency::with(
    [
        'exchangeRate' => function ($q) use ($days) {
            $latest = CurrencyExchangeRate::select('currency_id', 'date')
                ->selectRaw('MAX(created_at) created_at')
                ->groupBy('currency_id', 'date');
            $q->joinSub($latest, 'latest', function($join) {
                $join->on('currency_exchange_rates.currency_id', 'latest.currency_id')
                    ->on('currency_exchange_rates.date', 'latest.date')
                    ->on('currency_exchange_rates.created_at', 'latest.created_at');
            })->where('currency_exchange_rates.created_at', ">", strtotime('-' . $days . ' days', time()));
        }
    ]
)->get();

Ini mengeksekusi kueri berikut:

select *
from `currency_exchange_rates`
inner join (
  select `currency_id`, `date`, MAX(created_at) created_at
  from `currency_exchange_rates`
  group by `currency_id`, `date`
) as `latest`
on `currency_exchange_rates`.`currency_id` = `latest`.`currency_id`
  and `currency_exchange_rates`.`date` = `latest`.`date`
  and `currency_exchange_rates`.`created_at` = `latest`.`created_at`
where `currency_exchange_rates`.`currency_id` in (?, ...)
  and `currency_exchange_rates`.`created_at` > ?


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. MySQL - berapa lama membuat indeks?

  2. Mendapatkan jumlah baris dan data dari baris itu dalam satu kueri menggunakan PDO di PHP

  3. Menggunakan Alias ​​Kolom dalam Klausa SELECT yang Sama

  4. Bagaimana saya bisa mengukur waktu mysql, waktu dan/atau memuat kueri sql di php?

  5. Apa yang setara dengan REF CURSOR Oracle di MySQL?