如何对数据库中的数据进行分组

时间:2018-09-04 11:41:09

标签: php mysql sql group-by

我想基于episodes.id_eepisodes.id_mp_e对数据进行分组。

运行此代码时

SELECT * 
    FROM  link_relation, 
          episodes, 
          master_post 
   WHERE link_relation.id_mp_lr = master_post.id_mp 
     AND episodes.id_mp_e = master_post.id_mp 
     AND episodes.no_e = link_relation.no_e_lr 
    GROUP BY episodes.id_e 
    ORDER BY episodes.tanggal_e DESC`


The result what I am getting is :

id_mp_e       no_e         column_n
============  ===========  ===============
1             EP02         xxxxxxxxx
2             EP01         xxxxxxxxx
2             EP01         xxxxxxxxx
1             EP01         xxxxxxxxx
1             EP01         xxxxxxxxx

我要对id_mp_eno_e进行分组才能获得这样的结果

id_mp_e       no_e         column_n
============  ===========  ===============
1             EP02         xxxxxxxxx
2             EP01         xxxxxxxxx
1             EP01         xxxxxxxxx

上方的表仅显示id_mp_eno_e的值。

2 个答案:

答案 0 :(得分:1)

您似乎在错误的列上分组了。您在哪里:

GROUP BY episodes.id_e

您应该指定要分组的列:

GROUP BY episodes.id_mp_e, episodes.no_e

答案 1 :(得分:0)

只需使用逗号分隔,在episodes.id_mp_e子句中再添加一个字段(GROUP BY

SELECT * FROM  link_relation, episodes, master_post 
WHERE link_relation.id_mp_lr = master_post.id_mp 
AND episodes.id_mp_e = master_post.id_mp 
AND episodes.no_e = link_relation.no_e_lr 
GROUP BY episodes.id_mp_e, episodes_no_e
ORDER BY episodes.tanggal_e DESC