473,789 Members | 3,060 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2129
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_i n) 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_i n) 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_i n) 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_i n ) FROM guestbook AS gsub
-> GROUP BY name;
+------+--------------------+
| id | MAX(gsub.time_i n ) |
+------+--------------------+
| 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
5264
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 works as expected. But >>> numb=10 >>> cursor.execute("SELECT * FROM mytest where clientID = %d",numb) Traceback (innermost last): File "<stdin>", line 1, in ?
0
10215
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 database table, using dynamic sql. Executing 'EXEC SQL DESCRIBE SELECT LIST FOR S INTO select_dp;' the error code -2149 is returned That means "Specified partition does not exist". Does anybody know if it is a database problem or a problem of
2
1160
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 retrieve additional data. Is it better to so one big SELECT / JOIN / WHERE statement? As in SELECT * FROM T1 JOIN T2 ON T2. = T1.
3
6472
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 COULD be wrong... :) I've tried the access group...twice...and all I get is "Access doesn't like ".", which I know, or that my query names are too long, as there's a limit to the length of the SQL statement(s). But this works when I don't try to...
1
3690
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 "access_log", the referential integrity triggers generate these queries: SELECT 1 FROM ONLY "public"."application_type" x
19
8384
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 FOR UPDATE, it is fine and no error. I also tried Set objRs = objConn.Execute("SELECT * FROM EMP UPDATE OF EMPNO"), but it still couldn't help. any ideas? I tried to search in the web but couldn't find similar
1
1925
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 conditiion to restrict the results to only those records which have no DATE_COMPLETED data in them? Thanks in advance, Rick
12
2246
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, so I created report version 2. I want a same Command Button to open the appropriated version report for the specific month. I create a table with the following Fields: Month, ReportID, ReportToOpen (this is the exact report name). On a form,...
1
2823
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 I'm trying to fix includes a form which takes entered data, concatenates it into a VB string to form an SQL query, then launches a report with information from the query. Several tables are linked in the query, but the key ones for this problem...
0
9665
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9511
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10408
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10139
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9020
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6768
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5417
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4092
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3697
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.