We help IT Professionals succeed at work.

# Accessing variables in MySQL query

on
175 Views
I'm not highly skilled in SQL, and my query isn't working, and I'd like to know what I'm doing wrong.  I'm trying to write a query in MySQL to calculate a median.  My logic is straightforward:

1) Calculate position of median value based on number of entries in table, call this number n.
2) Select the nth row of ordered values in table based on numbering rows with a variable

The first query that calculates the value 'n' works fine.  The second query will return all the values as row number and Lat number from the Station table when I set the Where clause to be 'Where 1' instead of what's written below.

``````set @n = (SELECT Truncate(Count(S.Lat_N)/2,0) as N FROM STation AS S);
SELECT @rownum:=@rownum+1 as `row_number`, S.Lat_N
FROM Station S,  (SELECT @rownum:=0) r
--WHERE 1
WHERE @rownum = @n
ORDER BY S.Lat_N;
``````

The table name is Station and I'm focused on the column named Lat_N.

When I expand the Where clause as written, I get no results.  In some variations it complains it doesn't know what rownum is or what n or @n are either, but I'm just trying to figure out this first part.

What would be the proper way to accomplish the task of selecting the nth row as I'm trying to do above?
Comment
Watch Question

## View Solution Only

CERTIFIED EXPERT
Top Expert 2013

Commented:
You need to use a subquery for this:

``````set @n = (SELECT Truncate(Count(S.Lat_N)/2,0) as N FROM STation AS S);
SELECT * FROM(
SELECT @rownum:=@rownum+1 as `row_number`, S.Lat_N
FROM Station S,  (SELECT @rownum:=0) r
--WHERE 1
ORDER BY S.Lat_N) as a
WHERE row_number = @n;
``````

Commented:
Great, thank you.  Can you explain why the subquery is necessary and why my original query didn't work?
CERTIFIED EXPERT
Top Expert 2013
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)

Commented:
Great, thank you for the help.