I have a table name "test" having a column code (string format) and data is like:
U298765
U298799
U210430
U210499
B239856
Now I want to get data by input field entry. If a user write U298750, I want show the nearest value U298765 and for U210401,U210430.
You can use the right function to fetch the number and then use following logic.
Select t.*
From test t
Order by abs(Right(code, length(code)-1) - Right(your_input, length(your_input)-1))
Limit 1
I am consodering that you need the nearest based on numbers only.
Try below query:
select code from test
order by abs(abs(substring(code,2,length(code)))-abs(substring('U298750',2,length('U298750'))))
Limit 1
In place of 'U298750' use your input
You seem to just want:
select t.*
from t
where code >= ? -- the input value
order by code desc
limit 1;
The ordering of strings alphabetically is sufficient for getting the "next" value after the string. There is no need to convert anything to numbers.
Related
I have a PHP array with numbers of ID's in it. These numbers are already ordered.
Now i would like to get my result via the IN() method, to get all of the ID's.
However, these ID's should be ordered like in the IN method.
For example:
IN(4,7,3,8,9)
Should give a result like:
4 - Article 4
7 - Article 7
3 - Article 3
8 - Article 8
9 - Article 9
Any suggestions? Maybe there is a function to do this?
Thanks!
I think you may be looking for function FIELD -- while normally thought of as a string function, it works fine for numbers, too!
ORDER BY FIELD(field_name, 3,2,5,7,8,1)
You could use FIELD():
ORDER BY FIELD(id, 3,2,5,7,8,1)
Returns the index (position) of str in the str1, str2, str3, ... list. Returns 0 if str is not found.
It's kind of an ugly hack though, so really only use it if you have no other choice. Sorting the output in your app may be better.
Standard SQL does not provide a way to do this (MySQL may, but I prefer solutions that are vendor-neutral so I can switch DBMS' at any time).
This is something you should do in post-processing after the result set is returned. SQL can only return them in an order specified in the "order by" clause (or in any order if there's no such clause).
The other possibility (though I don't like it, I'm honor-bound to give you the choice) is to make multiple trips to the database, one for each ID, and process them as they come in:
select * from tbl where article_id = 4;
// Process those.
select * from tbl where article_id = 7;
// Process those.
: : : : :
select * from tbl where article_id = 9;
// Process those.
You'll just need to give the correct order by statement.
SELECT ID FROM myTable WHERE ID IN(1,2,3,4) ORDER BY ID
Why would you want to get your data ordered unordered like in your example?
If you don't mind concatening long queries, try that way:
SELECT ID FROM myTable WHERE ID=1
UNION
SELECT ID FROM myTable WHERE ID=3
UNION
SELECT ID FROM myTable WHERE ID=2
I have a SQL query in my php file (I use this file to calculate graphic timeblocks based on starting time and duration of an event; starttime and duration are my columns in SQL table).
How can I print/get last or first value from selection below using php? I mean first or last value from column 'starttime' to be precise.
$query1=mysqli_query($db,"select * from LISTS where category='planner'
order by date,timestart asc");
I googled since I am very much beginner but results did not make much sense because I don't have much skills yet. Therefore I am asking you.
Thanks in advance. Also can you please explain in very primitive way, some terms I might not understand at this point.
If you wan't both the first and last value in one MySql state you can use "Union". The UNION operator is used to combine the result-set of two or more SELECT statements.
To get either first or last value use "limit" and set this to 1, then order by asc or desc.
Example:
select * from LISTS where category='planner' order by date,timestart asc
limit 1) union (select * from LISTS where category='planner' order by
date, timestart desc limit 1
So I decided to find only first value based on my selection. I had to show it on the page, this is what worked for me.
$query3=mysqli_query($db,"select datetime from LISTS where
category='planner' order by date,timestart asc");
$SelectionArray=mysqli_fetch_array($query3);
$FIRSTdatetime=reset($SelectionArray);
echo $FIRSTdatetime;
I have a MySQL table set up with a field called clicks. It contains the clicks on certain banners separated by space (e.g. "9 80 47 306"). The field's type is text.
I want to get the entire table row and sort by whatever the last value in that field is (in this case it would be 306).
What I have so far doesn't work (obviously):
SELECT * FROM banners WHERE active = "1" ORDER BY clicked DESC
Is there a way I can achieve this using SQL only?
Thanks in advance!
Use substring_index() with -1:
SELECT *
FROM banners
WHERE active = "1"
ORDER BY substring_index(clicked, ' ', -1) DESC;
I should add that I agree that this is a bad way to store data. You should have a junction/association table. This would have one row per banner with a clicks column.
EDIT:
As the Joachim's comment wisely notes, we might want to change this to a number for sorting. In MySQL, I prefer + 0 because it does not report errors:
SELECT *
FROM banners
WHERE active = "1"
ORDER BY substring_index(clicked, ' ', -1) + 0 DESC;
Ugg, storing numbers as strings.
Try something like:
Order by substr(clicked,length(clicked-3),3)
I'm trying to calculate a percentual...and I need to sum all values from a column (Its already ok) but I need divide the result by number of rows...
select sum(voto) from tablename where id = numberHere
use COUNT to get the totalNumber of rows.
SELECT SUM(voto) / (COUNT(*) * 1.0)
FROM tablename
WHERE id = numberHere
by adding * 1.0 on the query will allow decimal places on the result.
or simply as
SELECT AVG(voto)
FROM tablename
WHERE id = numberHere
JW's answer is correct if you're looking specifically to do it by Summing/Dividing, but SQL has a function for that.
SELECT AVG(voto) FROM tablename WHERE id = numberHere
AFAIK, it automatically returns the same type as you input (except date columns, which should be parsed to seconds then re-encoded to date).
AVG should work, count(*) should work, you can also use ##rownum to get the number of rows returned by the statement if you need to do more with that number.
In a case where I have a column that needs to be unique eg. product:eggs, tomatoes, pepper, pepper1, pepper2
and before i insert another pepper i need to check the last integer, and add 1 to it, so the next pepper would be 'pepper3'
How would i do this?
Thanks in advance
The easy way is to have two columns: the first for the label and the second for the id.
It's never good to mix up various information in the same column.
Then you could do something like :
SELECT MAX(product_id) FROM ... WHERE label = "pepper"
and
SELECT CONCAT(label,product_id) FROM ... WHERE id = ...
Returns what you want.
I would try something like this:
SELECT LEFT(product_name, 6) AS product_name_plain,
CAST(RIGHT(product_name, 6) AS UNSIGNED) AS product_number
FROM product_table
WHERE product_name_plain = "pepper"
ORDER BY product_number DESC
LIMIT 1
The SELECT breaks apart product names into the plain name ("pepper"), and an unsigned integer version of the product number (3).
The WHERE clause identifies the peppers.
The ORDER BY will sort them (which should result in the last pepper being the first result)
The LIMIT will only fetch the one result.
Note that "6" and "pepper" are hard-coded in this query, your code would have to put them in. 6 is the length of "pepper."