Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

MySQL query with a variable which results randomly change

Problem with a particular query

11:33 am on Nov 14, 2011 (gmt 0)

New User

10+ Year Member

joined:June 28, 2007
posts: 17
votes: 0


I have a query that seems it changes its result randomly. I supose that I'm doing something wrong but when I review my query I don't find it. I hope you could help me.

The query orders the results and I use a variable for getting the row position:

SET @row_number_old :=0;
SELECT p.id, p.name, f.id, f.others, s.value, s.old_value, (
@row_number_old := @row_number_old +1
) AS old_position
FROM profile p
INNER JOIN other_table f ON f.profile_id = p.id
INNER JOIN score s ON s.profile_id = p.id
ORDER BY old_value DESC

Despite the data stored in the DB is always the same, the problem is that 'old_position' value is not always the same in the results. Sometimes it has the correct value (the row position), but another times it has the value of f.id inexplicably.
7:29 pm on Jan 2, 2012 (gmt 0)


WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:July 31, 2003
votes: 2

Is it because of your ORDER BY? It seems that could be the issue. Also, although you may be OK in this query, for future reference you may want to be careful reading and setting in the same SELECT query:

While it is also possible both to set and to read the value of the same variable in a single SQL statement using the := operator, this is not recommended. Section 8.4, “User-Defined Variables”, explains why you should avoid doing this.


Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members