PHP mysqli按组和随机选择

时间:2016-01-07 15:40:49

标签: php mysqli

不确定这是否可行。我试图让mysqli查询工作,将结果组合在一起,然后在每个组内随机显示结果。这是我当前的代码,它只是以随机顺序生成所有结果。

select * from swt_counties_members 
where 
  county_id=".$sCounty[1]." 
AND 
  status=1 
OR 
  county_id=0 
AND 
  status=1 
order by rand()

我需要做的是按service_id分组,然后随机显示每组中的记录。像这样的东西

select * from swt_counties_members 
where 
  county_id=".$sCounty[1]." 
AND 
  status=1 
OR 
  county_id=0 
AND 
  status=1 
group by service_id 
order by rand()

它将首先按service_id对所有结果进行分组,然后在每个组中随机显示结果

希望有道理:) 非常感谢

1 个答案:

答案 0 :(得分:1)

你想要ORDER BY,而不是GROUP BY

select * from swt_counties_members where county_id=".$sCounty[1]." AND status=1 OR county_id=0 AND status=1 order by service_id,rand()