MySQL上的视图和连接问题

时间:2017-01-02 18:32:13

标签: mysql

我有这个SQL,但返回相同的结果,而empresas表有超过15,000行,如果我使用JOIN返回170行,如果我使用LEFT JOIN返回15,000行,但在更长的时间内:

SELECT
`e`.`id_empresa` AS `id_empresa`,
`e`.`nome_fantasia` AS `nome_fantasia`,
`e`.`email` AS `email`,
`e`.`slug` AS `slug`,
`e`.`tags` AS `tags`,
`e`.`endereco` AS `endereco`,
`e`.`telefone` AS `telefone`,
`e`.`site_empresa` AS `site_empresa`,
`e`.`atividade_principal` AS `atividade_principal`,
`e`.`responsavel` AS `responsavel`,
`e`.`observacoes` AS `observacoes`,
`e`.`matriz` AS `matriz`,
`e`.`filial` AS `filial`,
`e`.`template` AS `template`,
`e`.`template_cor` AS `template_cor`,
concat(`c`.`nome`, '/', `c`.`uf`) AS `cidade`,
`c`.`id` AS `IDCIDADE`,
`p`.`plano` AS `plano`,
`p`.`logo` AS `logo`,
`p`.`data_vencimento` AS `data_vencimento`,
sum(`a`.`nota_total`) / count(`a`.`id_empresa`) AS `total`
FROM `empresas` `e`
LEFT JOIN `empresas_avaliacao` `a` ON `e`.`id_empresa` = `a`.`id_empresa`
LEFT JOIN `tb_cidades` `c` ON `e`.`cidade` = `c`.`id`
LEFT JOIN `empresas_premium` `p` ON `e`.`id_empresa` = `p`.`id_empresa`
GROUP BY `a`.`id_empresa`

1 个答案:

答案 0 :(得分:0)

INNER JOIN 从一个表中获取第二个表中有一些相关条目的所有记录

LEFT JOIN 从LEFT链接表中获取所有记录,但如果您从RIGHT表中选择了一些列,如果没有相关记录,则这些列将包含NULL。它返回左表中的所有行,即使右表中没有匹配项。