使用GROUP BY和JOIN进行MySQL查询

时间:2017-02-02 14:10:51

标签: mysql sql

下午好,

我试图从我的MySQL数据库中获取一些信息而我遇到了问题,因为我无法获得所需的信息。我尝试了很多不同的方法,但没有一种方法有效。我希望你能找到一些东西,因为我非常接近找到解决方案,但缺少一些东西:

MySQL查询:

SELECT b.id, b.tipo_perfil, round(avg(b.edad)), COUNT(c.zona), c.zona 
FROM analizador_datos_usuario AS a 
INNER JOIN analizador_datos_perfil AS b ON (a.id_usuario = b.id_perfil)
INNER JOIN analizador_datos_perfil_historial AS c ON (b.id = c.id_perfil)
WHERE a.id_usuario=21 
GROUP BY b.tipo_perfil, c.zona  
ORDER BY b.tipo_perfil ASC, count(c.zona) DESC

此查询为我提供了以下信息:

表格(红色表示我需要的内容):

enter image description here

亲切的问候,

2 个答案:

答案 0 :(得分:1)

试试:

SELECT  b.tipo_perfil, round(avg(b.edad)), COUNT(distinct c.zona), group_concat(distinct b.id separator ' ') as id_list, group_concat(distinct c.zona separator ' ') as zona_list
FROM analizador_datos_usuario AS a 
INNER JOIN analizador_datos_perfil AS b ON (a.id_usuario = b.id_perfil)
INNER JOIN analizador_datos_perfil_historial AS c ON (b.id = c.id_perfil)
WHERE a.id_usuario=21 
GROUP BY b.tipo_perfil
ORDER BY b.tipo_perfil ASC, count(distinct c.zona) DESC

答案 1 :(得分:0)

我认为你得到的结果显示的是你想要的红色结果。

尝试此修改后的查询: -

SELECT b.id, b.tipo_perfil, round(avg(b.edad)), COUNT(c.zona) counted_zone, c.zona 
FROM analizador_datos_usuario AS a 
INNER JOIN analizador_datos_perfil AS b ON (a.id_usuario = b.id_perfil)
INNER JOIN analizador_datos_perfil_historial AS c ON (b.id = c.id_perfil)
WHERE a.id_usuario=21 
GROUP BY b.tipo_perfil, c.zona  
Having MAX(counted_zone)
ORDER BY b.tipo_perfil ASC, counted_zone DESC