即使内连接不匹配,如何返回内容

时间:2017-03-21 12:46:36

标签: php mysql laravel eloquent

我有两张桌子

Cursos

+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| curso | varchar(255)     | NO   |     | NULL    |                |
+-------+------------------+------+-----+---------+----------------+

Trienios

+--------------+------------------+------+-----+---------+----------------+
| Field        | Type             | Null | Key | Default | Extra          |
+--------------+------------------+------+-----+---------+----------------+
| id           | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| data_trienio | varchar(255)     | NO   |     | NULL    |                |
| curso_id     | int(11)          | NO   |     | NULL    |                |
| oe_id        | int(11)          | NO   |     | NULL    |                |
+--------------+------------------+------+-----+---------+----------------+

那些表是通过关系连接的(通过curso_id看到),我想进行一个查询,在那里我检索curso记录和与每一个相关的trienio记录的数量

所以我在laravel

中完成了这个查询
$curso = Curso::select([
            'cursos.curso',
            \DB::raw('count(trienios.curso_id) as count')
        ])->join('trienios', 'trienios.curso_id', '=', 'cursos.id')
        ->groupBy('trienios.curso_id');

转换为此

select `cursos`.`curso`,
       count(trienios.curso_id) as count
from `cursos`
inner join `trienios`
    on `trienios`.`curso_id` = `cursos`.`id`
group by `trienios`.`curso_id`

它让我得到了与它们相关的trienios的cursos数量。然而,它只给那些拥有许多与它们相关的trienios的人。其他没有与它们相关的trienios的人不会被查询,我想查询它们。那么,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

使用leftJoin(),选择cursos.id,然后按cursos.id分组:

$curso = Curso::select([
        'cursos.id',
        DB::raw('count(trienios.curso_id) as count')
    ])->leftJoin('trienios', 'trienios.curso_id', '=', 'cursos.id')
    ->groupBy('cursos.id');

这是我想要运行的查询:

SELECT c.id,
       COUNT(t.curso_id) AS count
FROM cursos c
LEFT JOIN trienios t
    ON t.curso_id = c.id
GROUP BY c.id

LEFT JOIN应阻止cursos的记录被删除,即使它们在trienios中没有匹配的对应项。至于您看到的错误,您选择了cursos.curso,这不是聚合,而是没有出现在GROUP BY子句中。当MySQL在only_full_group_by时,这是不允许的,因此我将select子句更改为cursos.id