I need to search record as per status id in some sequence - mysql

My sql fiddle : http://sqlfiddle.com/#!9/012138/1
I have following table :
products (TABLE)
id INT(10)
productname VARCHAR(50)
statusid INT(10)
Suppose we have following records:
id productname statusid
5 P1000 2
6 P2000 1
7 P3000 3
Now you can see that status id is 1,2,3. I want to get record as per status id, but status id which we store is in different way so i can not write query to search as per order by statusid directly. Because i need to fetch record as per following status id order
first statusid 3, then status id 1 and then status id 2. How is it possible to write query ?

You can try using FIND_IN_SET
SELECT
*
FROM products
ORDER BY FIND_IN_SET(statusid,'3,1,2')
WORKING DEMO
Note:
Add your custom sequence here FIND_IN_SET(statusid,'3,1,2')
Brief note on FIND_IN_SET:
Description
MySQL FIND_IN_SET() returns the position of a string if it is present (as a substring) within a list of strings. The string list itself is a string contains substrings separated by ‘,’ (comma) character.
This function returns 0 when search string does not exist in the string list and returns NULL if either of the arguments is NULL.
Syntax
FIND_IN_SET (search string, string list)
Arguments
Name Description
search string A string which is to be looked for in following list of arguments.
string list List of strings to be searched if they contain the search string.
Related post
Alternatively you can use FIELD() function to accomplish that

Or use FIELD:
select *
from products
order by field(statusid, 3, 1, 2)
Demo Here

Related

Sorting of mixed alphanumerical strings - Postgresql

For an employee table i need to sort the list by the employeenumber (char). The input for this field is a string that can include any combination of alphanumerical and special characters. The desired output order is resembling Natural ordering.
Examples of common input:
Numbers only: {2,4,10,20,400,403,405} -> should be sorted as numbers
Alphanumeric: {A20,A30,B10,C30,C300} -> should be sorted alphabetically
Numbers with special chars: {4,4-1,10,15,15-2,17,20}
Control sample {B-33,-14,17B,A18,#62,A 76,C25,3-34,1,3,10,33,45,101,302}
I already have this working with MySql adding the following to the order by:
CAST(employeenumber AS SIGNED), employeenumber
For postgresql I have tried the following that works if the input only contains integers:
CASE
WHEN employeenumber~E'^[\\d\\s]+$'
THEN CAST (employeenumber AS INTEGER)
ELSE 0
END
Working mysql example:
SELECT
employeenumber
FROM
employee
ORDER BY
CAST(employeenumber AS SIGNED), employeenumber;
Input: {1,2,30,12b}
Output: {1,2,12b,30}
So for postgresql the I'm currently working with 2 options:
Query 1(Q1):
SELECT employeenumber FROM employee ORDER BY employeenumber;
Query 2(Q2):
SELECT employeenumber FROM employee ORDER BY CASE WHEN employeenumber~E'^[\\d\\s]+$' THEN CAST (employeenumber AS INTEGER) ELSE 0 END
Input: {1,2,30,12b}
Expected/preferred output: {1,2,12b,30} or {1,2,30,12b}
Output Q1: {1,12b,2,30}
Output Q2: {12b,1,2,30}
I have been able to get acceptable results if the input set is restricted to fx numbers only or alphanumeric, but as soon as special characters are introduced or if the Q2 is used on an alphanumeric set it gives problems.
Running Q2 on the Control sample gives the following result:
{B-33,-14,17B,A18,C25,#62,A 76,3-34,1,3,10,33,45,101,302}
The numerical part is ordered as expected, but the alphanumeric/special char part is all kinds of jumbled.

Can't extract JSON Paths in Queries

Hi I have a table "status" with 2 column id and string.
I insert one data for example id = 1 and string = {"1": "Enable", "2": " Disabled"}.
How can I only get the value "Enable" in SQL?
If I type SELECT
id, string->"$.1"
FROM status;
I have Invalid JSON Path expression.
You need to to wrap the 1 in quotation marks so it is treated as a string, not a number.
Either of these should work for you:
SELECT id, string->"$.\"1\""
FROM status
or:
SELECT id, string->'$."1"'
FROM status
There is a function for that called json_extract().
Following query should get the job done:
SELECT
id,
json_extract(string,'$.1')
FROM status;
Edit: This solution will only work for Mysql 5.7 or later versions.
Hope it helps!

MySQL Query where id = id_product error

i'm working with mysql in a nodejs web app. I don't understand why when I ask for some id (key) it gives me more than 1 result.
When I:
SELECT * FROM products WHERE id = 1;
This happens, I get 3 results, but I only want 1:
1, 001 and 0000001.
I just want the info of one product (id: 1 in this example)
How can I fix this?
ID type is varchar(20)
If I use LIKE instead of = my result changes:
SELECT * FROM products WHERE id LIKE 0000001;
I get the info of id = 1 instead 0000001. Don't know why.
Thanks
The WHERE clause of your query contains a comparison of a literal numeric value with a string (column id).
When it needs to compare values of different type, MySQL uses several rules to convert one or both of the values to a common type.
Some of the type conversion rules are not intuitive. The last rule is the only one that matches a comparison of an integer number with a string:
In all other cases, the arguments are compared as floating-point (real) numbers.
When they are converted to floating-point (real) numbers, 1 (integer), '1', '0001' and '0000001' are all equal.
In order to get an exact match the literal value you put in the query must have the same type as the column id (i.e string). The query should be:
SELECT * FROM products WHERE id = '1'
The problem is that you are looking by a varchar type using an integer cast.
Try to add quotes to the id parameter:
SELECT * FROM products WHERE id = '1';
If you want to add integer ids with with leading zeros, I recommend you to use the zerofill option:
https://dev.mysql.com/doc/refman/5.5/en/numeric-type-attributes.html
If you want to use use alphanumeric values then keeps the ID type as varchar, but remember to enclose the search param into quotes.
Numbers in MySQL (and the real world) don't have leading zeros. Strings do.
So, you just need to make the comparison using the right type:
SELECT *
FROM products
WHERE id = '1';
What happens with your original query is that the id is converted to a number. And '1', '001' and '0000001' are all converted to the same integer -- 1. Hence, all three pass the filter.

MySQL SELECT WHERE id IN function()

I have a function that returns VARCHAR.
It will be always empty string "" OR single ID "1" OR IDs "1,2,3,4,5".
Then I have this query:
SELECT id, title FROM category WHERE id IN getIds(1);
But it returns only first item because it is as a string, eg. 1, instead if 1,2,3.
Is there a way to tell MySQL it should use it not as a string?
Since MySQL does not support table-valued functions. You have 2 choices:
1) Use FIND_IN_SET https://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set AND http://www.w3resource.com/mysql/string-functions/mysql-find_in_set-function.php "This function returns the location of a string given in the first argument of the function, in a comma-separated list in a string given in the second argument. The first element of the list is 1. A 0 is returned if the string is not found in the set. It returns NULL if either argument is NULL."
SELECT id, title FROM category WHERE FIND_IN_SET(id, getIds(1)) > 0
2) Populate a temp table and use it with the IN operator
SELECT id, title FROM category WHERE id IN (SELECT Id FROM myTempTable)
Approach #1 seems more appropriate for this case.

I have a mysql query where I give value of a column in list " WHERE IN" and I want to order my result same order I give in list. Is it possible?

I have a mysql query where I give value of a column in list " WHERE IN" and I want to order my result same order I give in list. Is it possible?
My SQL query is like
SELECT *
FROM <TABLE NAME>
WHERE id IN (2,12,56,5,9)
I want the result to be in same order as I gave inside my list i.e. 2,12,56,5,9
SELECT *
FROM table_name
WHERE name IN (2,12,56,5,9)
ORDER BY FIELD(id,2,12,56,5,9)
Returns the index (position) of id in the 2,12,56,5,9 list. Returns 0 if str is not found.
If all arguments to FIELD() are strings, all arguments are compared as strings. If all arguments are numbers, they are compared as numbers. Otherwise, the arguments are compared as double.
FIELD()
Yes, it's possible.
SELECT ...
ORDER BY
CASE
WHEN id = 2 THEN 1
WHEN id = 12 THEN 2
WHEN id = 56 THEN 3
...
END