sql >> Database >  >> RDS >> Mysql

GROUP BY en ORDER BY samen gebruiken in LARAVEL 5.6

Gebruik een 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();

Dit voert de volgende query uit:

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. Hoe maak ik verbinding met een SQL Server 2008-database met behulp van JDBC?

  2. MySQL ::SQL-instructie uitvoeren binnen variabele

  3. Databaseontwerp voor gebruikersinstellingen

  4. Maven - java.lang.ClassNotFoundException:com.mysql.jdbc.Driver