There is a field 'noticeBy' enum('email','mobile','all','auto','nothing') NOT NULL DEFAULT 'auto'. As it known ordering by ENUM field performs relative to its index. However, how it possible make order by its values?
As documented under Sorting:
ENUM values are sorted based on their index numbers, which depend on the order in which the enumeration members were listed in the column specification. For example, 'b' sorts before 'a' for ENUM('b', 'a'). The empty string sorts before nonempty strings, and NULL values sort before all other enumeration values.
To prevent unexpected results when using the ORDER BY clause on an ENUM column, use one of these techniques:
Specify the ENUM list in alphabetic order.
Make sure that the column is sorted lexically rather than by index number by coding ORDER BY CAST(col AS CHAR) or ORDER BY CONCAT(col).
Per the second bullet, you can therefore sort on the column after it has been cast to a string:
ORDER BY CAST(noticeBy AS CHAR)
This also works:
ORDER BY FIELD(noticeBy, 'all','auto','email','mobile','nothing')
(I don't believe that there is a setting to achieve this, you have to provide the sort-values.)
You can define your order however you wish:
ORDER BY CASE noticeBy
WHEN 'email' THEN 1
WHEN 'mobile' THEN 2
WHEN 'all' THEN 3
WHEN 'auto' THEN 4
ELSE 5
END
This will return the rows in the following order: email, mobile, all, auto, nothing.
In my case, I had to sort enum results by the "ENUM" field and also make sure the values are in DESCENDING order. My enum had the following values: 'Open','Closed'
So when I used ORDER BY CAST(status AS CHAR), the results were in this order:
Closed
Open
Open
But I wanted the Open status tickets to be shown first and then the Closed tickets. So I used the following:
ORDER BY CAST(status AS CHAR) DESC
This gave me the order that I was looking for i.e.
Open
Open
Closed
Summary:
Just using ORDER BY CAST on an enum did not seem to help. To sort the results in a specific order, mentioning ASC or DESC as well, did the trick.
The best option to me:
ORDER BY FIELD(status, 'publish','not-publish','expirated','deleted'), creation DESC
Status is the field in my BBDD, and values in '' are the values that has in enum options.
I hope that help u too! :)
Related
Struggling this the following sql statment.
The database is MySQL with score being DECIMAL(5,1)
Im looking to order by the average score within the column
...AVG(COALESCE(score,0)) AS scoreAvg ... ORDER BY scoreAvg DESC
but the results are not as expected, I have products with a high score below ones without a score (score is 0).
It lookings like score is being treated as a string, I have tried.
CAST(SCORE AS DECIMAL(5,1))
but with no luck.
Thank you for any help,
Regards
Try repeating the expression:
ORDER BY AVG(COALESCE(score, 0))
The first explanation that I think of is that scoreavg is already in a table and the ordering is using the column rather than the computed expression.
Your value might be in varchar(max)
So you want to convert the varchar to decimal or numeric and add
Order by avg(COALESCE(column name,0))
Or
Order by avg(coalesce(cast(column name as decimal (5,1)),0.0)
After stripping down my sql string, turns out my "image_path" column in TEXT format was causing the issue. Changed it to varchar(255).
I did'nt post it because I didnt think it was relevent.
anyway fixed now.
Must be a bug in MySQL
This case is similar to: S.O Question; mySQL returns all rows when field=0, and the Accepted answer was a very simple trick, to souround the ZERO with single quotes
FROM:
SELECT * FROM table WHERE email=0
TO:
SELECT * FROM table WHERE email='0'
However, my case is slightly different in that my Query is something like:
SELECT * FROM table WHERE email=(
SELECT my_column_value FROM myTable WHERE my_column_value=0 AND user_id =15 LIMIT 1 )
Which in a sense, becomes like simply saying: SELECT * FROM table WHERE email=0, but now with a Second Query.
PLEASE NOTE: It is a MUST that I use the SECOND QUERY.
When I tried: SELECT * FROM table WHERE email='( SELECT my_column_value FROM myTable WHERE my_column_value=0 LIMIT 1 )' (Notice the Single Quotes on the second query)
MySql SCREAMED Errors near '(.
How can this be achieved
Any Suggestion is highly honored
EDIT1: For a visual perspective of the Query
See the STEN_TB here: http://snag.gy/Rq8dq.jpg
Now, the main aim is to get the sten_h where rawscore_h = 0;
The CURRENT QUERY as a whole.
SELECT sten_h
FROM sten_tb
WHERE rawscore_h = (
SELECT `for_print_stens_rowscore`
FROM `for_print_stens_tb`
WHERE `for_print_stens_student_id` =3
AND `for_print_stens_factor_name` = 'Factor H' )
The result of the Second Query can be any number including ZERO.
Any number from >=1 Works and returns a single corresponding value from sten_h. Only =0 does not Work, it returns all rows
That's the issue.
CORRECT ANSWER OR SOLUTION FOR THIS
Just in case someone ends up in this paradox, the Accepted answer has it all.
SEE STEN_TB: http://snag.gy/Rq8dq.jpg
SEE The desired Query result here: http://snag.gy/wa4yA.jpg
I believe your issue is with implicit datatype conversions. You can make those datatype conversions explicit, to gain control.
(The "trick" with wrapping a literal 0 in single quotes, that makes the literal a string literal, rather than a numeric.)
In the more general case, you can use a CAST or CONVERT function to explicitly specify a datatype conversion. You can use an expression in place of a column name, wherever you need to...
For example, to get the value returned by my_column_value to match the datatype of the email column, assuming email is character type, something like:
... email = (SELECT CONVERT(my_column_value,CHAR(255)) FROM myTable WHERE ...
or, to get the a literal integer value to be a string value:
... FROM myTable WHERE my_column_value = CONVERT(0,CHAR(30)) ...
If email and my_column_value are just indicating true or false then they should almost certainly be both BIT NOT NULL or other two-value type that your schema uses for booleans. (Your ORM may use a particular one.) Casting is frequently a hack made necessary by a poor design.
If it should be a particular user then you shouldn't use LIMIT because tables are unordered and that doesn't return a particular user. Explain in your question what your query is supposed to return including exactly what you mean by "15th".
(Having all those similar columns is bad design: rawscore_a, sten_a, rawscore_b, sten_b,... . Use a table with two columns: rawscore, sten.)
I am having column named rating in the mysql database table with multiple values from 1+,2+,................9+,10+,12+. when i am sorting this column with query
select * from tbl_app order by rating desc
I am getting 9+ as highest value, can any one tell me how to get 12+ as highest value
SELECT rating,SUBSTR(rating,1,LENGTH(rating)-1) FROM tbl_app ORDER BY CAST(SUBSTR(rating,1,LENGTH(rating)-1) as SIGNED) DESC;
if the last char is always a '+',the sql above will work.
what have you kept the datatype of the column rating ? If you have kept it varchar or text then this query will not work for sorting values as per descending order.
Probably the easiest thing to do in MySQL is cast those odd looking strings to numbers:
order by cast(rating as unsigned) desc
-- or less explicitly
order by rating + 0 desc
Both of those casts will stop trying to convert the string to a number when they hit the + so you'll get them sorted numerically.
Simply removing the plus signs from the strings will still leave you with strings and '10' < '2' is just as true for strings as '10+' < '2+'. That's actually your whole problem: you're storing numbers as decorated strings when you should be storing them as integers and adding the + decorations when you display them. You really should fix your schema to make sense instead of adding ugly hacks to work around your schema's strange ideas.
try this :
select convert(replace(rating,'+',' '),unsigned integer) as x from tab order by x desc
sql_fiddle_demo
I'm getting weird results on a MySQL SELECT statement that uses ORDER BY my_column ASC.
It's ordering the results the way a "computer" would order them, instead of a human:
Item F: 241.565853
Item B: 25.310854
Item D: 25.397155
Item C: 260.252356
Item A: 27.7740
Item E: 271.774058
How do I get it to ORDER BY in the correct manner? My SELECT statement has a couple LEFT JOINS-- not sure if that would make a difference.
Any suggestions on how to correct this problem?
Something like this should do it:
ORDER BY ABS(my_column) ASC
The column you're ordering by is most likely a string-based (varchar, text, etc) datatype. You're seeing lexically-correct ordering for such a datatype. Change the column to use a numeric datatype, or (less-preferably, because why are you storing a numeric value as a string) cast the column to a numeric type and perform the sort on that cast.
I hope there's a simple solution for this:
I have a table where each row has it's own status (SET type field). Statuses can be:
offline
available
busy
distance
I'd like to order as follows
available
busy
distance
offline
I thought a simple
ORDER BY `status` ASC
will do the trick (alphabetical order) but it gives me the following:
offline
available
busy
distance
How can is sort out this in the most simple way?
Thanks in advance,
fabrik
SELECT * FROM table ORDER BY FIELD(status,'offline','available','busy','distance')
see Mysql order by specific ID values
Thought I'd add another way to order by custom field values,
ORDER BY FIND_IN_SET(status, 'available,busy,distance,offline')
(If the given strings contain a quote simply escape it)
You could also do something like this, if reordering the SET values in impractical:
... ORDER BY CASE `status`
WHEN 'available' THEN 1
WHEN 'busy' THEN 2
WHEN 'distance' THEN 3
WHEN 'offline' THEN 4
END
Simpler than the solutions above:
ORDER BY CONCAT(status)
Nevermind.
The trick is saving SET values at the right order.