SQL group by returns just first row

蓝咒 提交于 2019-12-11 10:15:48

问题


I have a table which contains two columns 'id' and 'layout plan'

I need to see all those rows which have the same layout plan

I use this query.

select * 
from project_layout 
group by layout_plan 
having count(layout_plan) > 1

But this query is only returning the first row.

I want to see all the groups with the same layout plan.


回答1:


Databases other than MySQL would give an error if you use a column that's not grouped without an aggregate. But MySQL will return an indeterminate value from among the group's rows.

To retrieve all the rows in layout_plan groups with more than one row, you could use:

select  *
from    project_layout
where   layout_plan in
        (
        select  layout_plan 
        from    project_layout 
        group by 
               layout_plan 
        having 
               count(*) > 1
        )



回答2:


Try this,

select * from project_layout 
where layout_plan in (select layout_plan   
            from project_layout    
            group by layout_plan   
            having count(layout_plan) > 1)



回答3:


Select  a.*
from    project_layout
        INNER JOIN 
        (
            select  layout_plan 
            from    project_layout 
            group   by  layout_plan 
            having  count(layout_plan ) > 1
        ) b ON a.layout_plan = b.layout_plan

for faster performance, add an index on column layout_plan



来源:https://stackoverflow.com/questions/14769929/sql-group-by-returns-just-first-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!