Jump to content

grab unique rows


aebstract

Recommended Posts

$query = mysql_query("SELECT * FROM calendar WHERE MONTH(caldate) = '$calmonth2' && YEAR(caldate) = '$calyear' ORDER BY DAY(caldate) LIMIT 1") or DIE(mysql_error());

 

I have 4 rows, they have a field called event_tag. I want to grab 1 result from each unique event_tag. My query is obviously wrong, but I'm hoping I'm close and not much needs to be changed. Thanks

Link to comment
https://forums.phpfreaks.com/topic/190590-grab-unique-rows/
Share on other sites

I have 4 rows, they have a field called event_tag. I want to grab 1 result from each unique event_tag. My query is obviously wrong, but I'm hoping I'm close and not much needs to be changed. Thanks

 

How do you decide which of the 4 rows for an event tag that you want to bring back. If you just want a list of the event tags then the code Hybride gives should do fine. However if you want the (say) latest row of the 4 for an event tag then something different is required (and could do with the table layout to help there).

 

All the best

 

Keith

Link to comment
https://forums.phpfreaks.com/topic/190590-grab-unique-rows/#findComment-1005400
Share on other sites

Hi

 

Cheap and nasty way to do it

 

$query = mysql_query("SELECT * FROM calendar WHERE MONTH(caldate) = '$calmonth2' && YEAR(caldate) = '$calyear' ORDER BY DAY(caldate) GROUP BY event_tag LIMIT 1") or DIE(mysql_error());

 

Won't work in most flavours of SQL but MySQL seems to manage it.

 

All the best

 

Keith

Link to comment
https://forums.phpfreaks.com/topic/190590-grab-unique-rows/#findComment-1005495
Share on other sites

Hi

 

:'( . Made a mistake. The ORDER BY clause has to go after the GROUP BY clause

 

$query = mysql_query("SELECT * FROM calendar WHERE MONTH(caldate) = '$calmonth2' && YEAR(caldate) = '$calyear' GROUP BY event_tag ORDER BY DAY(caldate) LIMIT 1") or DIE(mysql_error()); 

 

Although I suspect you don't want the LIMIT 1 there (which was in your original SQL.

 

$query = mysql_query("SELECT * FROM calendar WHERE MONTH(caldate) = '$calmonth2' && YEAR(caldate) = '$calyear' GROUP BY event_tag ORDER BY DAY(caldate)") or DIE(mysql_error()); 

 

All the best

 

Keith

Link to comment
https://forums.phpfreaks.com/topic/190590-grab-unique-rows/#findComment-1005510
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.