473,387 Members | 1,456 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Looking for SELECT statement

mysql> select * from guestbook;
+----+--------+---------+-----------------+----------------+
| id | fname | lname | comments | time_in |
+----+--------+---------+-----------------+----------------+
| 1 | Mick | White | Test 123 | 20050303191815 |
| 2 | Ann | White | Hello World | 20050303191931 |
| 3 | Ann | White | It's a nice day | 20050303191959 |
| 4 | Seamus | White | The cat | 20050303192028 |
| 5 | Matt | White | Words of wisdom | 20050303192509 |
| 6 | Sharon | Pombert | In the sticks | 20050303221802 |
| 7 | Tony | Jones | Cousin | 20050303222027 |
| 8 | Tony | Jones | Cousin's cousin | 20050303222133 |
| 9 | Matt | Dye | UR | 20050303222133 |
+----+--------+---------+-----------------+----------------+

I am trying to retrieve each person's latest comment. i.e every record
except id's 2 & 7 in this case.
Is this possible?
Mick
Jul 23 '05 #1
4 2107
Mick White wrote:
mysql> select * from guestbook;
+----+--------+---------+-----------------+----------------+
| id | fname | lname | comments | time_in |
+----+--------+---------+-----------------+----------------+
| 1 | Mick | White | Test 123 | 20050303191815 |
| 2 | Ann | White | Hello World | 20050303191931 |
| 3 | Ann | White | It's a nice day | 20050303191959 |
| 4 | Seamus | White | The cat | 20050303192028 |
| 5 | Matt | White | Words of wisdom | 20050303192509 |
| 6 | Sharon | Pombert | In the sticks | 20050303221802 |
| 7 | Tony | Jones | Cousin | 20050303222027 |
| 8 | Tony | Jones | Cousin's cousin | 20050303222133 |
| 9 | Matt | Dye | UR | 20050303222133 |
+----+--------+---------+-----------------+----------------+

I am trying to retrieve each person's latest comment. i.e every record
except id's 2 & 7 in this case.
Is this possible?


Yes, it's possible, but it's tricky. SQL doesn't provide a very
seamless solution for problems like this. You're trying to group by one
colums (or set of columns in this case, fname + lname), aggregate by
another column (time_in), and then get the value from a third column
(comments).

Here's one possible solution:

SELECT g1.fname, g1.lname, g1.comments
FROM guestbook AS g1 INNER JOIN
(SELECT gsub.id, MAX(gsub.time_in) FROM guestbook AS gsub
GROUP BY gsub.fname, gsub.lname) AS g2
ON (g1.id = g2.id);

Since this uses subqueries, you must be using at least MySQL 4.1.

Regards,
Bill K.
Jul 23 '05 #2
Bill Karwin wrote:
Mick White wrote:
mysql> select * from guestbook;
+----+--------+---------+-----------------+----------------+
| id | fname | lname | comments | time_in |
+----+--------+---------+-----------------+----------------+
| 1 | Mick | White | Test 123 | 20050303191815 |
| 2 | Ann | White | Hello World | 20050303191931 |
| 3 | Ann | White | It's a nice day | 20050303191959 |
| 4 | Seamus | White | The cat | 20050303192028 |
| 5 | Matt | White | Words of wisdom | 20050303192509 |
| 6 | Sharon | Pombert | In the sticks | 20050303221802 |
| 7 | Tony | Jones | Cousin | 20050303222027 |
| 8 | Tony | Jones | Cousin's cousin | 20050303222133 |
| 9 | Matt | Dye | UR | 20050303222133 |
+----+--------+---------+-----------------+----------------+

I am trying to retrieve each person's latest comment. i.e every record
except id's 2 & 7 in this case.
Is this possible?

Yes, it's possible, but it's tricky. SQL doesn't provide a very
seamless solution for problems like this. You're trying to group by one
colums (or set of columns in this case, fname + lname), aggregate by
another column (time_in), and then get the value from a third column
(comments).

Here's one possible solution:

SELECT g1.fname, g1.lname, g1.comments
FROM guestbook AS g1 INNER JOIN
(SELECT gsub.id, MAX(gsub.time_in) FROM guestbook AS gsub
GROUP BY gsub.fname, gsub.lname) AS g2
ON (g1.id = g2.id);

Since this uses subqueries, you must be using at least MySQL 4.1.


Thanks, Bill. Unfortunately, I am using 4.0.23. I appreciate your
response. Interesting.
Mick
Jul 23 '05 #3
Bill Karwin wrote:
SELECT gsub.id, MAX(gsub.time_in) FROM guestbook AS gsub
GROUP BY gsub.fname, gsub.lname


Are you sure this returns the id mathing the max-value in row?

AFAIK, the max value will be indeed the largest value, but the id will
be from undefined row inside the group of matching rows. (In case of
MySQL, I think it will return id from the first row)

Simplified example:
mysql> select * from guestbook;
+------+------+----------------+
| id | name | time_in |
+------+------+----------------+
| 1 | Mick | 20050303191815 |
| 3 | Ann | 20050303191815 |
| 2 | Mick | 20050303191931 |
| 4 | Ann | 20040303191931 |
+------+------+----------------+

mysql> SELECT gsub.id, MAX(gsub.time_in ) FROM guestbook AS gsub
-> GROUP BY name;
+------+--------------------+
| id | MAX(gsub.time_in ) |
+------+--------------------+
| 3 | 20050303191815 |
| 1 | 20050303191931 |
+------+--------------------+

Compare time_in values from first query and second for id 1:
20050303191815 and 20050303191931

As you can see, they don't match, so the returned id is not connected to
the returned maximum value. And if the inner query in your subquery
returns invalid values, the outer query will also return invalid values.
Please correct me if you think the subquery works correctly in this case
or with 4.1, I don't have much experience with those.
Jul 23 '05 #4
Aggro wrote:
Please correct me if you think the subquery works correctly in this case
or with 4.1, I don't have much experience with those.


No, you're absolutely right! I am very sorry to have suggested the
solution, since it doesn't work.

This points out the trouble with this type of aggregation query in SQL.
When using GROUP BY, the only fields that are safe to reference in the
select-list but not in an aggregation function are columns named in your
GROUP BY statement.

In other words, in this case:

SELECT A, B, MAX(C)
FROM table
GROUP BY A

The value of A is invariant in the grouping, and the value of C is
well-defined as the maximum value of field C in that grouping. But the
value of B is ambiguous.

In some RDBMS implementations, it's actually a semantic error to execute
a query with this ambiguity, and the query fails if you try to do that.

MySQL permits you (wrongly, in my opinion) to execute this type of
query, and it chooses a more or less arbitrary value to return for those
fields. As Aggro points out, it seems to choose the "first" row in the
group (but this is a coincedence of implementation, and not due to any
rule, since there is no such thing as an implicit ordering of rows in a
table).

So for Mick's solution, we can only use fields in the subquery that are
part of the aggregate expression, or are referenced in the GROUP BY
clause. I'm going to make an assumption that the id field is used in
such a way that a greater id value for a given guest is guaranteed to
correspond to a greater value for time_in. That is, MAX(time_in) always
occurs on the same row as MAX(id) for a given guest.

SELECT gsub.fname, gsub.lname, MAX(gsub.id)
FROM guestbook AS gsub
GROUP BY gsub.fname, gsub.lname

This gives us the max comment id per guest, which is also known to be
the most recent entry for that respective guest. Now make a
comma-separated string of all the values of id returned by the above
query, and use it when building the following query (we have to build
the SQL query as a string, because simple parameter substitution with ?
doesn't support lists of values).

SELECT g1.fname, g1.lname, g1.comments
FROM guestbook AS g1
WHERE g1.id IN ( $idlist )

This should work, doesn't violate the grouping-column rule, and doesn't
require subqueries.

Regards,
Bill K.
Jul 23 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
by: John Fabiani | last post by:
Hi, I'm a newbie and I'm attempting to learn howto create a select statement. When I use >>> string1='18 Tadlock Place' >>> cursor.execute("SELECT * FROM mytest where address = %s",string1) All...
0
by: Jan | last post by:
I store sql-commands in a database table. In the first step I get the sql command out of the database table with embedded sql. In the second step I try to execute the command, which i got from the...
2
by: JayCallas | last post by:
This is more a theoretical question so I do not have any DDL (working) to post. Let's say that I have a query which needs to be filtered for specific accounts while also needing several joins to...
3
by: Tcs | last post by:
My backend is DB2 on our AS/400. While I do HAVE DB2 PE for my PC, I haven't loaded it yet. I'm still using MS Access. And no, I don't believe this is an Access question. (But who knows? I...
1
by: Grant McLean | last post by:
Hi First a simple question ... I have a table "access_log" that has foreign keys "app_id" and "app_user_id" that reference the "application_type" and "app_user" tables. When I insert into...
19
by: Steve | last post by:
ASP error number 13 - Type mismatch with SELECT...FOR UPDATE statement I got ASP error number 13 when I use the SELECT...FOR UPDATE statement as below. However, if I use SELECT statement without...
1
by: Rick | last post by:
I'm trying to do a SELECT statement looking for a DATE_COMPLETED field which is blank, meaning it has not been completed. The DATE_COMPLETED field is a DATE type field. How do I specify my WHERE...
12
by: Orchid | last post by:
Hello all, I have different version of reports which used for different months. For example, I am using report version 1 up to September, but we have some design changes on the report for October,...
1
by: Randy Volkart | last post by:
I'm trying to fix a glitch in a complex access database, and have a fairly complex problem... unless there's some obscure easy fix I don't know being fairly new with Access. Basically, the area...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.