Friday 30 August 2019

Mysql Tutorial | Give Priority To Specific Values In Select Query Using ...



Query Examples









1) SELECT * FROM
`employee` order by FIELD(name,"steve rogers","loki")
desc
2) SELECT * FROM
`employee` order by FIELD(salary, id IN (select id from employee
where salary > 300 and salary < 800))








Hello guys.
This tutorial will
be about how to give more priority to specific values in SELECT query
of mysql database server without where clause. And how to fix the
error “subquery returns more than 1 row”. In order by field. For
example, what if you want employee should have more priority where
the salary between 300 and 700 then the rest will be displayed.
The application of
using this will be, getting data which are more related to topic like
google search.
As you can see, i
have one employee table, so instead of using where clause, I am going
to use order by Field, the FIELD is a function, the first argument
will be the calumn name that you want to be ordered, then in other
arguments, you can specify which values you specifically want, in my
case its steve and loki. Make sure to type “DESC” to make sure
that they come on top of list.
But what if you
don’t know how many data should have more priority or if the list
is too large, in that case, we shall use the subquery.
In my case, I want
to give prioritize by salary, so first argument will be salary, and
in second argument, in subquery I am going to call primary key, which
is ID, then apply the condition of salary between 300 and 800.
As you can see, it
is giving me the error that “it is returning more than one row ”
which is obvious. So to fix it, just apply condition “id in”
before subquery.
In result, you can
see that all the data is coming, but employee between salary 300 and
700 have more priority.
Thank you for
watching, dont forget to like share and subscribe.

No comments:

Post a Comment