I have three tables joined by left join. Here's the code:
SELECT
(LEAST(`a`.`price, `b`.`price`) - `c`.`price`) AS `diff`
...
ORDER BY `diff` DESC
The problem: c.price is greater than the LEAST, thus the subtraction is negative and throws BIGINT UNSIGNED value is out of range.
How can I make it NOT throw this ridiculous error?
This is result data, I'm not modifying the actual data in the table, so why does it not allow me to do this normally?
I've tried CAST(LEAST(...) AS SIGNED) and casting both columns inside LEAST as signed, neither worked.
Cast as SIGNED each number before LEAST and before substract
SELECT
(LEAST(CAST(`a`.`price` AS SIGNED), CAST(`b`.`price` AS SIGNED)) - CAST(`c`.`price` AS SIGNED)) AS `diff`
...
ORDER BY `diff` DESC
You may want to check the NO_UNSIGNED_SUBTRACTION operator: http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html#sqlmode_no_unsigned_subtraction.
There are risks in using it, though: http://datacharmer.blogspot.fi/2006/11/hidden-risks-of-sql-mode.html
Related
For some reason I have to explicitly cast a BIT(1) MySQL column as UNSIGNED in order to get back a 0 or 1 IF I include that column as part of a subquery but not as a "normal" query. Allow me to elaborate...
I have two database tables: contests and votes
CONTESTS - id, ..., ...
VOTES - ..., over BIT(1), ..., ...
If I run this query I get results I would expect...
SELECT votes.over as vote_over FROM votes WHERE votes.contest_id = 38;
Result:
vote_over: 1 (ok, this makes sense)
If, however, I try to select votes.over as a subquery, I get a curious result...
SELECT contests.id as contest_id,
(SELECT over FROM votes WHERE votes.contest_id = contests.id) as vote_over
FROM contests
where contests.id = 38;
Result:
contest_id: 38
vote_over: 49 (WHAT?)
Why is vote_over (a bit column) 49 if it's a subquery, but 1 if it's included in the vanilla query above??! And what is the significance of 49? Why not 2377? 49 is 110001 and this problem would make a little more sense if I had defined the 'over' column as a bit(6) type, but it's a bit(1). This makes no sense!
After some futzing around, I happened upon this query that gave me what I wanted...
SELECT `contests`.id as contest_id,
(SELECT cast(`votes`.over as unsigned) FROM (`votes`) WHERE votes.contest_id = contests.id)
FROM (`contests`) as vote_over
where contests.id = 38;
Result:
contest_id: 38
vote_over: 1
So while I've found a way to get what I wanted out of the query, I don't understand why casting the vote_over result as unsigned makes a difference ONLY in a subquery.
Additional info: I'm running these queries on a MySQL 5.6.14 instance on my laptop. Obviously these queries are just hypotheticals to illustrate the problem I've isolated. They don't make much sense by themselves and I typed them up in the course of debugging a much larger query where that subquery is necessary.
It seems like there's something fundamental that I don't understand about signing bits in subqueries that this problem is exposing. Please help!
This is because SELECT [bit_column] is not supposed to return a printable result set in the first place. You are just lucky that it sometimes returns something intelligible.
http://dev.mysql.com/doc/refman/5.6/en/bit-field-literals.html:
Bit values are returned as binary values. To display them in printable form, add 0 or use a conversion function such as BIN().
On my box, SELECT [bit_column] always returns non-printable characters.
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 have one table trip_data.Every one second i getting packets and inserting data to database.trip_data table contains four fields.trip_paramid,fuel_content,creation_time&vehicle_id.I want to select all rows in which difference between creation time is 2 minutes(Not exactly 2.Approximately 2).trip_data table contains 40 lacks rows.So i need a optimized select query for this.Can anyone help on this.Here is table schema&sample data for the trip_table..
SQlFiddle demo
SELECT
tp.*
FROM
trip_parameters tp
GROUP BY
CONVERT(UNIX_TIMESTAMP (tp.creation_time)/(2*60), unsigned)
ORDER BY
tp.creation_time asc
Note that using UNIX_TIMESTAMP does not allow you to handle dates beyond year 2037. Using the following instead fixes the problem:
CONVERT(TIMESTAMPDIFF(SECOND,'1970-01-01 00:00:00',tp.creation_time)/(2*60), unsigned)
You can do it in one table scan using MYSQL User defined variables. Unfortunately UDV's have a limited set of data types (integer, decimal, floating-point, binary or nonbinary string). So in this query I use a char #ti varible to store previous datetime using CAST to compare it with the Creation_time field. Also initial value for this variable I set to (now()-10000000) you can use any date you wish less than MIN(Creation_time)
Here is the SQLFiddle demo
select * from
(
select trip_parameters.*,
if(ABS(TIMESTAMPDIFF(MINUTE,Creation_time,cast(#ti as datetime)))>=2,1,0) t,
#ti:=if(ABS(TIMESTAMPDIFF(MINUTE,Creation_time,cast(#ti as datetime)))>=2,
cast(Creation_time as char(100)),#ti)
from trip_parameters,
(select #ti:=cast(now()-10000000 as char(100))) a
order by creation_time
) t2
where T=1
order by creation_time
Try this
SELECT trip_paramid, fuel_content, creation_time, vehicle_id
FROM trip_parameters
GROUP BY FLOOR(UNIX_TIMESTAMP(creation_time)/120)
This takes one item of every 2 minute block
I have a field number of type varchar. Even though it is of type varchar, it stores integer values with optional leading zeros. A sort orders them lexicographically ("42" comes before "9"). How can I order by numeric values ("9" to come before "42")?
Currently I use the query:
SELECT * FROM table ORDER BY number ASC
Try this
SELECT * FROM table_name ORDER BY CAST(field_name as SIGNED INTEGER) ASC
There are a few ways to do this:
Store them as numeric values rather than strings. You've already discounted that as you want to keep strings like 00100 intact with the leading zeros.
Order by the strings cast as numeric. This will work but be aware that it's a performance killer for decent sized databases. Per-row functions don't really scale well.
Add a third column which is the numeric equivalent of the string and index on that. Then use an insert/update trigger to ensure it's set correctly whenever the string column changes.
Since the vast majority of databases are read far more often than written, this third option above amortises the cost of the calculation (done at insert/update) over all selects. Your selects will be blindingly fast since they use the numeric column to order (and no per-row functions).
Your inserts and updates will be slower but that's the price you pay and, to be honest, it's well worth paying.
The use of the trigger maintains the ACID properties of the table since the two columns are kept in step. And it's a well-known idiom that you can usually trade off space for time in most performance optimisations.
We've used this "trick" in many situations, such as storing lower-cased versions of surnames alongside the originals (instead of using something like tolower), lengths of identifying strings to find all users with 7-character ones (instead of using len) and so on.
Keep in mind that it's okay to revert from third normal form for performance provided you understand (and mitigate) the consequences.
Actually i've found something interesting:
SELECT * FROM mytable ORDER BY LPAD(LOWER(mycol), 10,0) DESC
This allows you to order the field like:
1
2
3
10
A
A1
B2
10A
111
SELECT * FROM table ORDER BY number + 0
Trick I just learned. Add '+0' to the varchar field order clause:
SELECT * FROM table ORDER BY number+0 ASC
I now see this answer above. I am wondering if this is typecasting the field and an integer. I have not compared performance. Working great.
For a table with values like Er353, ER 280, ER 30, ER36
default sort will give
ER280
ER30
ER353
ER36
SELECT fieldname, SUBSTRING(fieldname, 1, 2) AS bcd,
CONVERT(SUBSTRING(fieldname, 3, 9), UNSIGNED INTEGER) AS num
FROM table_name
ORDER BY bcd, num;
the results will be in this order
ER30
ER36
ER280
ER353
you can get order by according to your requirement my using following sql query
SELECT * FROM mytable ORDER BY ABS(mycol)
given a column username containing VARCHAR's like these:
username1
username10
username100
one could do:
SELECT username,
CONVERT(REPLACE(username, 'username', ''), UNSIGNED INTEGER) AS N
FROM users u
WHERE username LIKE 'username%'
ORDER BY N;
it is not cheap, but does the job.
SELECT * FROM table ORDER BY number ASC
Should display what you want it to display.. looks like you're sorting it by id or number is not defined as integer at the moment.
MySQL ORDER BY Sorting alphanumeric on correct order
example:
SELECT `alphanumericCol` FROM `tableName` ORDER BY
SUBSTR(`alphanumericCol` FROM 1 FOR 1),
LPAD(lower(`alphanumericCol`), 10,0) ASC
output:
0
1
2
11
21
100
101
102
104
S-104A
S-105
S-107
S-111
Another option to keep numerics at a top, then order by alpha.
IF(name + 0, name + 0, 9999999), name
Rough and ready: order by 1*field_name
I'm run this query:
SELECT id,like - dislike as result
FROM mytable
Where the column like and dislike are unsigned integer. If the column dislike is greater than like mysql return number like 18446744073709551596, so seem that mysql treat this like unsigned and can't return negative number but continue the computation from a sort of MAX_UNSIGNED_INT. How can I have the correct result
Try casting the two values (or maybe only on of them)
SELECT id, convert(like, SIGNED ) - convert(dislike, SIGNED ) as result
FROM mytable
or only the result
SELECT id, convert(like - dislike, SIGNED ) as result
FROM mytable
In the first way you can get type overflow! The Second way is better, but I'm not sure it works with mysql.
You could try casting them as Int:
SELECT id, CAST(like AS INT) - CAST(dislike AS INT) as result FROM mytable