MySQL查询结合join,group by,having和order by子句

时间:2018-08-31 12:52:34

标签: mysql

$date = $this->db->select('crv.date')
            ->from('commodities com')
            ->where('com.id = ' . $row->id)
            ->join('curves crv', 'com.curve_id = crv.profile_id', 'left')
            ->group_by('crv.date')
            ->having('COUNT(DISTINCT crv.job_id) = ' . $nr_commodities)
            ->order_by('crv.date DESC')
            ->limit(1)
            ->get()->row();

我需要在mysql中转换以上查询:

我尝试了以下方法。但出现一些语法错误。任何帮助将不胜感激。

select crv.date
from commodities com
  where com.id = 100
left join curves crv on com.curve_id = crv.profile_id
group by crv.date
  having COUNT(DISTINCT crv.job_id) = 4
order by crv.date DESC
           limit 1

1 个答案:

答案 0 :(得分:0)

使用

select crv.date
from commodities com
left join curves crv on com.curve_id = crv.profile_id
where com.id = 100
group by crv.date
  having COUNT(DISTINCT crv.job_id) = 4
order by crv.date DESC
           limit 1