tags:

views:

78

answers:

5

If I say:

select max(length(Name)) 
  from my_table

I get the result as 18, but I want the concerned data also. So if I say:

select max(length(Name)), 
       Name 
  from my_table

...it does not work. There should be a self join I guess which I am unable to figure it out.

Can anyone please provide me a clue?

Thanks,

A: 

Edited, will work for unknown max() values:

select name, length( name )
from my_table
where length( name ) = ( select max( length( name ) ) from my_table );
CJohn
yes, but i want the concerned `name` which has maxlenght of 18
JPro
ok I managed to get what I want like this `select max(length(Name)) as num1,Name from my_table group by Name having num1 = 18`, since I know from the first query that max is 18. But how to combine this to one query?
JPro
Ah, okay, I misread that. In MS SQL I would use select Name from my_table where length(Name) = (select max(length(Name)) from my_table), but I am fairly certain that is not correct MySQL syntax.
CJohn
A: 

I suppose you could use a solution such as this one :

select name, length(name)
from users
where id = (
    select id
    from users
    order by length(name) desc
    limit 1
);

Might not be the optimal solution, though... But seems to work.

Pascal MARTIN
+1  A: 
select * 
from my_table 
where length( Name ) = ( 
      select max( length( Name ) ) 
      from my_table
      limit 1 
);

It this involves two table scans, and so might not be very fast !

Martin
The limit in the sub-query is unnecessary: max() is an aggregation operator and will only return 1 row.
Martin
+1  A: 

Use:

  SELECT mt.name 
    FROM MY_TABLE mt
GROUP BY mt.name
  HAVING MAX(LENGTH(mt.name)) = 18

...assuming you know the length beforehand. If you don't, use:

  SELECT mt.name 
    FROM MY_TABLE mt
    JOIN (SELECT MAX(LENGTH(x.name) AS max_length
            FROM MY_TABLE x) y ON y.max_length = LENGTH(mt.name)
OMG Ponies
is this the optimal one?
JPro
@JPro: Check the explain plan, but I think Quassnoi's is likely the most optimal.
OMG Ponies
+3  A: 
SELECT  name, LENGTH(name) AS mlen
FROM    mytable
ORDER BY
        mlen DESC
LIMIT 1
Quassnoi
+1: For simplicity, or "why didn't I think of that"
OMG Ponies
+1 - yes, ditto.
Martin