MySQL SELECT PER组首次进入PER组

时间:2016-11-11 22:14:59

标签: php mysql sql

我有一个名为worksheets_items的表,类似于这个设置

table "worksheet_items"
ID    DATE_ADDED    COUNTY_ID    NAME    COMPLETED
1     2016/03/15    11           "ZA"    0
2     2016/03/15    12           "FB"    1
3     2016/03/15    12           "GC"    0
4     2016/03/15    13           "GD"    1
5     2016/03/15    11           "EE"    1
6     2016/03/15    13           "TF"    1
7     2016/03/16    11           "YG"    0
8     2016/03/16    11           "WH"    0
9     2016/03/16    12           "YI"    1
10    2016/03/16    13           "QJ"    0
11    2016/03/16    13           "RK"    1
12    2016/03/16    12           "UL"    0
13    2016/03/16    11           "PM"    1

我想要做的就是每个县每个日期获得一行(无论是否是第一行)。我的目标是在该日期显示日期和每个县,其中有任何条目COMPLETED = 0

所以在这种情况下,我希望最终得到

ID    DATE_ADDED    COUNTY_ID    NAME    COMPLETED
1     2016/3/15     11           "ZA"    0
3     2016/3/15     12           "GC"    0
7     2016/3/16     11           "YG"    0
12    2016/3/16     12           "UL"    0
10    2016/3/16     13           "QJ"    0

我尝试使用GROUP BY,但我在MySQL方面的专业知识有限,所以最终只是把错误抛出了wazoo。任何帮助都将非常感谢!

2 个答案:

答案 0 :(得分:0)

我认为你根本不需要GROUP_BY

您需要的是按date_added和county_id

订购记录
SELECT * FROM worksheet_items
WHERE completed=0
ORDER BY date_added, county_id

答案 1 :(得分:-1)

每个日期和县获取一个ID(例如最大ID)。然后使用找到的ID访问记录。

select *
from worksheet_items
where (date_added, county_id, id) in
(
  select date_added, county_id, max(id)
  from worksheet_items
  where completed = 0
  group by date_added, county_id
)
order by id;