473,770 Members | 7,287 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Trying to SELECT a SELF JOIN Max value

Hello All, Hope some Guru will be able to help me with this.

Let's take this example table

A
-------------------------------------------------------------------------------
id | TicketNo | evaluation | Username
-------------------------------------------------------------------------------
1 1 9 Jamie
2 1 8.5 Jocasta
3 1 9.1 Claire
4 2 9 Jamie
5 2 7.3 Fergus
6 3 6 Fergus
-------------------------------------------------------------------------------
Basically, what I want to do is

FIND all the TicketNo for which the Maximum evaluation have been given
by Jamie.

It should then return :

4 2 9 Jamie

and my TicketNo would be 2.
If I want the same query for Fergus, the result would be:
5 2 7.3 Fergus
6 3 6 Fergus

And if I want for Jocasta there will be an empty set.

I have try so many different request, but I assume my Query should be
something like

SELECT id,TicketNo,eva luation,Usernam e FROM A WHERE ....???

I suppose from here I should do a self JOIN on the table, joining the
TicketNo to the TicketNo, and finding the id with the MAXIMUM
"joinned" value of evaluation...

I'm getting headache!!

Please help!

Much thanks in advance!


Jul 20 '05 #1
4 10913
"Denis St-Michel" <ds*******@aei. ca> wrote in message
A
-------------------------------------------------------------------------- ----- id | TicketNo | evaluation | Username
-------------------------------------------------------------------------- ----- 1 1 9 Jamie
2 1 8.5 Jocasta
3 1 9.1 Claire
4 2 9 Jamie
5 2 7.3 Fergus
6 3 6 Fergus
-------------------------------------------------------------------------- -----

Basically, what I want to do is

FIND all the TicketNo for which the Maximum evaluation have been given
by Jamie.
Let's work towards a solution.

Which version of MySql are you using? Version 4.1 supports nested
sub-queries, meaning that in the where clause of a select statement you have
another select statement. I got a hunch those will come in handy here.

In earlier versions of MySql you can create a temporary table, do the
sub-query and store the results in this temporary table, then do the real
query which will join to this temporary table, then finally drop the
temporary table.
It should then return :

4 2 9 Jamie

and my TicketNo would be 2.
If I want the same query for Fergus, the result would be:
5 2 7.3 Fergus
6 3 6 Fergus
I don't understand why Fergus gave the largest evaluation for ticket 2.
Didn't Jamie give the highest evaluation, namely 9 points?

Let's clarify the algorithm you want, then we can come up with a SQL
statement.
And if I want for Jocasta there will be an empty set.

I have try so many different request, but I assume my Query should be
something like

SELECT id,TicketNo,eva luation,Usernam e FROM A WHERE ....???

I suppose from here I should do a self JOIN on the table, joining the
TicketNo to the TicketNo, and finding the id with the MAXIMUM
"joinned" value of evaluation...


Something like

SELECT id,TicketNo,eva luation,Usernam e FROM A WHERE EXISTS (SELECT ... FROM
A WHERE ...)

might work.

See my post with subject "find all products with maximum version" which you
can search in groups.google.c om with

find all products with maximum version group:mailing.d atabase.mysql

or if you can get this link to work:

http://groups.google.com/groups?hl=e...ic.15911%24_o3
..514673%40bgtn sc05-news.ops.worldn et.att.net&rnum =1&prev=/groups%3Fq%3Dfi nd%
2Ball%2Bproduct s%2Bwith%2Bmaxi mum%2Bversion%2 Bgroup:mailing. database.mysql% 2
6hl%3Den%26lr%3 D%26ie%3DUTF-8%26group%3Dmai ling.database.m ysql%26selm%3DX Dli
c.15911%2524_o3 .514673%2540bgt nsc05-news.ops.worldn et.att.net%26rn um%3D1
Jul 20 '05 #2
On Fri, 27 Aug 2004 04:29:50 GMT, "Siemel Naran"
<Si*********@RE MOVE.att.net> wrote:

Which version of MySql are you using? Version 4.1 supports nested
sub-queries, meaning that in the where clause of a select statement you have
another select statement. I got a hunch those will come in handy here.
I'ts 4.0.20-standard therefore it doesn't support nested
sub-queries...that' s too bad..

I don't understand why Fergus gave the largest evaluation for ticket 2.
Didn't Jamie give the highest evaluation, namely 9 points?


You're totally right.. my mistake..
I finally been able to do what I Wanted by building my request this
way:

SELECT t1.id,t1.Ticket No,t1.evaluatio n,t1.Username FROM A t1 INNER
JOIN A t2 ON t1.TicketNo = t2.TicketNo GROUP BY t1.id, t1.TicketNo,
t1.evaluation, t1.Username HAVING t1.evaluation = MAX(t2.evaluati on);

and it seems to be working well.
But I'm still concern about the efficiency. Is this the best way to do
it (considering I can't update to MySQL 4.1 for now) ..?

Thanks again,
Jul 20 '05 #3
"Denis St-Michel" <ds*******@aei. ca> wrote in message
I finally been able to do what I Wanted by building my request this
way:

SELECT t1.id,t1.Ticket No,t1.evaluatio n,t1.Username FROM A t1 INNER
JOIN A t2 ON t1.TicketNo = t2.TicketNo GROUP BY t1.id, t1.TicketNo,
t1.evaluation, t1.Username HAVING t1.evaluation = MAX(t2.evaluati on);

and it seems to be working well.


Clever! Only thing is you have to repeat the select columns in the group
by, which means lots of typing if you have more columns.
But you mentioned you want to find ticket numbers where a certain Username
gave the maximum evaluation. For this I think the following should work:

SELECT t1.id,t1.Ticket No,t1.evaluatio n,t1.Username
FROM
A t1
INNER JOIN A t2 ON t1.TicketNo = t2.TicketNo
where t1.Username = 'Fergus'
GROUP BY t1.id, t1.TicketNo, t1.evaluation, t1.Username
HAVING t1.evaluation = MAX(t2.evaluati on)
;

It's important to know what you're after, as you'd create different indexes
for each scenario: find ticket nos for which Username gave the maximum
evaluation as you said in the original post, or find the Username for every
ticket no who gave the maximum evaluation. They differ by just a where
clause on Username = ?. but may require different indices to optimize.
I think it should be efficient if you have an index on a ( TicketNo,
evaluation desc, Username ). Hopefully the engine drives by t2 on this
index, quickly finding the maximum evaluation for every ticket no, joins to
t1 on the same index using all three columns of the index. But running the
SQL in the control center shows it drives by t1 using no index, then joins
to t2 using the above index. Note: I may be reading the explain tab
incorrectly, but it lists t1 first then t2, so I think it's driving by t1.
And this even if I GROUP BY t1.TicketNo, t1.evaluation desc, t1.Username,
t1.id, or add an ORDER BY t1.TicketNo ..., or reverse the table list
(selecting from t2 first then t1).
Better yet, the engine realizes that the join to t1 selects the same row
(kind of) and so avoids the join, and instead just applies the where
Username = ? clause to determine whether to show this row or move on to the
next one.

Of course, in order to quickly find the maximum evaluation for each ticket
no, we'd like a special index: one way is that the index on ( TicketNo,
.... ) stores the TicketNo, followed by the number of records with this
TicketNo, followed by this many pointers to the original records. The
advantage of this data structure is that we can quickly find the maximum
evaluation for the first ticket no (it's the first record), then quickly
jump to the next ticket no (because we know the number of records to skip).
But I don't know what kind of indexes MySql uses, and create index does not
allow us to specify the type of index.
Note that the IN method (possible on version 4.1 and later) also drives by
no index on the outer table, then the index ( TicketNo, evaluation desc,
Username ) on t2. Again, this is assuming I'm reading the explain tab
correctly, which lists t1 first. Here goes:

select t1.id,t1.Ticket No,t1.evaluatio n,t1.Username
from A t1 where t1.evaluation = (
select max(evaluation)
from A t2
where t1.ticketno = t2.ticketno
)
and Username = 'Fergus'
;

We could try an index ( Username, TicketNo, evaluation desc ). It seems the
engine drives by t1, but only uses the first column of the index.
The select from view method

select t.id,t.TicketNo ,t.evaluation,t .Username
from A t,
(select t2.ticketno as ticketno, max(evaluation) as evaluation
from A t2 group by t2.ticketno) as tt
where
t.ticketno = tt.ticketno and t.evaluation = tt.evaluation
and t.Username = 'Fergus'
;

appears to drive by oops, what? The explain tab has me confused.
Finally, you could try the force index and related extension of MySql to try
to force a certain driving table and index. I haven't tried this though.
And you can explicitly do the inner query first by using temporary tables.

create temporary table A2 (
ticketno int,
evaluation double
);

insert into A2 (ticketno, evaluation)
select ticketno, max(evaluation)
from A
group by ticketno;

create index A2_index on A2 ( ticketno, evaluation );

select A.id,A.TicketNo ,A.evaluation,A .Username
from A inner join A2 on A.ticketno = A2.ticketno and A.evaluation =
A2.evaluation
where A.Username = 'Fergus'
;

Jul 20 '05 #4
On Sat, 28 Aug 2004 17:34:33 GMT, "Siemel Naran"
<Si*********@RE MOVE.att.net> wrote:

Wow, that was a crash course for me. I'm kind of new to MySQL. your
explanations are very welcomes and helps me getting even more
interested in MySQL.

thanks again!!

Dennis

Jul 20 '05 #5

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

Similar topics

1
2452
by: D. Shifflett | last post by:
Hi all, I am having trouble with a program that ran fine on Python 2.0 (#0, Mar 1 2001, 01:47:55) on linux2 but will not work on Python 2.3.2 (#1, Oct 8 2003, 17:33:47) on linux2
4
1371
by: Denis St-Michel | last post by:
Hello All, Hope some Guru will be able to help me with this. Let's take this example table A ------------------------------------------------------------------------------- id | TicketNo | evaluation | Username ------------------------------------------------------------------------------- 1 1 9 Jamie 2 1 8.5 ...
17
5029
by: kalamos | last post by:
This statement fails update ded_temp a set a.balance = (select sum(b.ln_amt) from ded_temp b where a.cust_no = b.cust_no and a.ded_type_cd = b.ded_type_cd and a.chk_no = b.chk_no group by cust_no, ded_type_cd, chk_no)
1
2077
by: dbuchanan | last post by:
VB.NET 2003 / SQLS2K The Stored Procedure returns records within Query Analyzer. But when the Stored Procedure is called by ADO.NET ~ it produced the following error message. --------------------------- Exception Message: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints. ---------------------------
0
1563
by: Mark Gifford | last post by:
Hi, I've inherited an Access database and need to create a form which will allow me to view and alter the data. I've created a new form and using a tip I got from this helpful site http://www.jmhare.com/wildhare2.htm , I've created two combo boxes, with the contents of the second combo box depending upon the value in the first. That's working fine though it took a while to get it working properly because I don't think the database is...
0
1917
by: Susan Bricker | last post by:
The following error: "The current field must match the join key '?' in the table that seves as t the 'one' side of one-to-many relationship. Enter a record in the 'one' side table with the desired key value, and then make the entry with the desired join key in the 'many-only' table." ... happens when I click on an entry of a combobox. HELP!! Here's the background:
2
8107
by: Ev | last post by:
I have a database table in SQL Server that has a self join. In C# I have a DataTable with a self-join. I have defined a foreign key constraint on the DataTable for the self join. The AcceptRejectRule is set to Cascade Table Structure: OrderID (Identity field) OrderDesc OrderParent (this is the self-join - it is a foreign key to OrderID) In my code I add several rows to the table, createing a hierarchy of orders
2
2329
by: comp.lang.php | last post by:
var $filterArray = array('reverse' =IMG_FILTER_NEGATE, 'edge highlight' =IMG_FILTER_EDGEDETECT, 'emboss' =IMG_FILTER_EMBOSS, 'gaussian blur' =IMG_FILTER_GAUSSIAN_BLUR, 'blur' =IMG_FILTER_SELECTIVE_BLUR, 'sketchy' =IMG_FILTER_MEAN_REMOVAL); I am trying to generate an HTML dropdown from this array, however, when
5
5068
by: RioRanchoMan | last post by:
I have a forum table where the field Forum_ID of the first thread corresponds to itself in the field Forum_Ancestor, and 0 (zero) for the field Forum_Parent when it is the first topic in a thread: Example of first topic in thread values ============================================= Forum_ID=13 (topic) Forum_Parent=0 Forum_Ancestor=13
22
12493
by: MP | last post by:
vb6,ado,mdb,win2k i pass the sql string to the .Execute method on the open connection to Table_Name(const) db table fwiw (the connection opened via class wrapper:) msConnString = "Data Source=" & msDbFilename moConn.Properties("Persist Security Info") = False moConn.ConnectionString = msConnString moConn.CursorLocation = adUseClient moConn.Mode = adModeReadWrite' or using default...same result
0
10230
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
10004
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
9870
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8886
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...
1
7416
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6678
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
5313
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...
0
5450
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3576
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.