Solved

Mysql GROUP BY, how to detect when new "group"?

Posted on 2015-02-19
4
62 Views
Last Modified: 2015-03-04
Hi,

When using "SELECT * FROM table GROUP BY city"

What is the best method to detect a new group/city?
I need to post a new html-table and list all related database records associated to each city.

Any suggestions?
0
Comment
Question by:kgp43
  • 2
4 Comments
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 40619363
Your SQL won't do what you think it will - it will simply return one record for each City - because you're grouping your records by City. The rest of the data shown for a record is likely to be from the first record in that City's group.

You may be better off writing your App to select the Distinct Cities, and then loop through that list, firing off another query to select records that match that city.
0
 

Author Comment

by:kgp43
ID: 40619396
You're right.
Think i'm going to use ORDER BY and then check if new city is different from previous one, if so: post table start and ending.

Think that will work?
0
 
LVL 43

Accepted Solution

by:
Chris Stanyon earned 500 total points
ID: 40619433
It will, but it doesn't feel like a clean way of doing it. Any reason to not do it the way I suggested. It's actually pretty easy. Here's a very quick demo using PDO:

<?php
$stmt = $dbh->prepare("SELECT * FROM table WHERE city = ?");

foreach ($dbh->query("SELECT DISTINCT city FROM table;") as $row):
	printf("<h1>City: %s</h1>", $row->city);
	
	echo "<table>";
	
	$stmt->execute( array($row->city) );
	while ($row = $stmt->fetch()):
		printf("<tr><td>%s</td><td>%s</td></tr>", $row->column1, $row->column2);
	endwhile;
	
	echo "</table>";
	
endforeach;
?>

Open in new window


Basically it selects a distinct list of cities, and loops through them. For each city it finds it pulls the matching records from your database, and displays a table containing the data.
0
 
LVL 48

Expert Comment

by:PortletPaul
ID: 40620621
"SELECT * FROM table GROUP BY city" is bad for 2 reasons (at least)

1. that * will produce changes that your downstream code may not be prepared for, it is a bug creator 'par excellence'

2. MySQL has this bizarre "feature" that allows this lazy syntax, and it "approximates" values for the fields (read: guesses)

In most flavours of SQL you MUST specify ALL the fields that will form a group, then ALL OTHER fields must be handled by an aggregate function like MAX() MIN() SUM() COUNT() etc.

The default settings of MySQL ignore this convention; and don't require the more stringent syntax. One risk is (if someone does alter the settings) and the system all of a sudden will require precise syntax and all previous lazy syntax grouping queries will fail. The other, perhaps more disturbing, risk is that the data in all the non-aggregated columns just isn't accurate and should be relied upon (unless you do enjoy "indeterminate" results).

MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. This means that the preceding query is legal in MySQL. You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate.
http://dev.mysql.com/doc/refman/5.0/en/group-by-handling.html (emphasis added)

Use these "lazy group bys" with caution IMHO
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question