Mysql can't use mysql if condition in order by - mysql

I want to write a select like this
if(`order` > 0)
Order BY category_id, arder
if(`order` = 0)
Order BY id
But in this select does not work
SELECT * from post
ORDER BY if(`order` > 0, ( category_id, `order`) , id)

"If" is an expression returns a value, I don't think you can use it to change the "order by" statement itself.
You can try something like this:
select *, case when order>0 then category_id else 0 end cat_id, id
from post
order by cat_id, order, id

Related

order by with union in SQL is not working

Is it possible to order when the data comes from many select and union it together? Such as
In this statement, the vouchers data is not showing in the same sequence as I saved on the database, I also tried it with "ORDER BY v_payments.payment_id ASC" but won't be worked
( SELECT order_id as id, order_date as date, ... , time FROM orders WHERE client_code = '$searchId' AND order_status = 1 AND order_date BETWEEN '$start_date' AND '$end_date' ORDER BY time)
UNION
( SELECT vouchers.voucher_id as id, vouchers.payment_date as date, v_payments.account_name as name, ac_balance as oldBalance, v_payments.debit as debitAmount, v_payments.description as descriptions,
vouchers.v_no as v_no, vouchers.v_type as v_type, v_payments.credit as creditAmount, time, zero as tax, zero as freightAmount FROM vouchers INNER JOIN v_payments
ON vouchers.voucher_id = v_payments.voucher_id WHERE v_payments.client_code = '$searchId' AND voucher_status = 1 AND vouchers.payment_date BETWEEN '$start_date' AND '$end_date' ORDER BY v_payments.payment_id ASC , time )
UNION
( SELECT return_id as id, return_date as date, ... , time FROM w_return WHERE client_code = '$searchId' AND w_return_status = 1 AND return_date BETWEEN '$start_date' AND '$end_date' ORDER BY time)
Wrap the sub-select queries in the union within a SELECT
SELECT id, name
FROM
(
SELECT id, name FROM fruits
UNION
SELECT id, name FROM vegetables
)
foods
ORDER BY name
If you want the order to only apply to one of the sub-selects, use parentheses as you are doing.
Note that depending on your DB, the syntax may differ here. And if that's the case, you may get better help by specifying what DB server (MySQL, SQL Server, etc.) you are using and any error messages that result.
You need to put the ORDER BY at the end of the statement i.e. you are ordering the final resultset after union-ing the 3 intermediate resultsets
To use an ORDER BY or LIMIT clause to sort or limit the entire UNION result, parenthesize the individual SELECT statements and place the ORDER BY or LIMIT after the last one. See link below:
ORDER BY and LIMIT in Unions
(SELECT a FROM t1 WHERE a=10 AND B=1)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2)
ORDER BY a LIMIT 10;

SQL Query - Search with SQL array results

Am trying this query to get result. but am not able to find any results. I don't know where i did the mistake.
Select * from loadcell_transaction_log where id =
(SELECT max(id) as id1
FROM [addpro].[dbo].[loadcell_transaction_log] group by line2_count);
This is the error am getting:
Msg 512, Level 16, State 1, Line 2
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Try this:
Select * from loadcell_transaction_log where id IN
(SELECT max(id) as id1
FROM [addpro].[dbo].[loadcell_transaction_log] group by line2_count);
I replace '=' with the keyword 'IN' which allows for multiple results in the subquery.
using group by with max(id) will return max(id) for each line2_count :
select * from
(select log.*,row_number() over (partition by line2_count order by id desc ) rn FROM [addpro].[dbo].[loadcell_transaction_log] as log)
where rn = 1;
If you want to check only for max(id) in the full table data then dont use group by clause else use in clause as referred by #farbiondriven.

Mysql LEFT to match first 3 chars

Im trying to get all matching records from the invoice_id field where the first 3 characters are RBK, case sensitivity not important. I've tried to use the LEFT function in the bottom 2 ways but its not working. Any ideas on how to achieve this?
SELECT *, IF( LEFT( invoice_id, 3) = 'RBK') FROM `invoices` ORDER BY id ASC
SELECT *, IF( LEFT( invoice_id, 3) = 'RBK', 3, 0) FROM `invoices` ORDER BY id ASC
an if inside the select is not to filter results,if you want to filter result use where clause.
SELECT * FROM `invoices` WHERE LEFT(invoice_id, 3) = "RBK" ORDER BY id ASC

Possible to add auto incrementing variable to row results of GROUP BY in mysql?

Basically, I'm using this query to group a bunch of users based on the sum of numbers associated with them. I need to some how assign an index to each result. I am blanking on how to do this. I'm thinking I need to alias something with AS but not sure quite how. Any ideas?
This is the current query where I switch out the page and per dynamically:
SELECT COUNT(*) as count, user_id, SUM(earnings) as sum FROM ci_league_result
GROUP BY user_id ORDER BY sum desc LIMIT ".$page.', '.$per;
I'm lookin for it to work something like this:
SELECT COUNT(*) as count, user_id, SUM(earnings) as sum, *NEW-RESULTS-OVERALL-INDEX* AS newindex FROM ci_league_result
GROUP BY user_id ORDER BY sum desc LIMIT ".$page.', '.$per;
notice the AS newindex in the second query.
Thanks for your advice!
Try this:
SELECT user_id, count, sum, #row := #row + 1 AS newindex FROM
(SELECT
COUNT(*) as count,
user_id,
SUM(earnings) as sum
FROM ci_league_result
GROUP BY user_id ORDER BY sum desc LIMIT ".$page.', '.$per) r
CROSS JOIN (SELECT #row := 0) rr;
EDITED
You should be able to accomplish this with SQL variables
SELECT
COUNT(*) as count,
user_id,
SUM(earnings) as sum,
#rownum := #rownum+1 AS newindex
FROM ci_league_result,
(SELECT #rownum:=0) r
GROUP BY user_id
ORDER BY sum DESC
LIMIT ".$page.', '.$per;

Where mistake in sql LIKE clause?

I try to count all items from another table with this select:
SELECT id, name, (SELECT count(*)
FROM prekes_main
WHERE prekes_main.pristKaina = 1
and prekes_main.pg_kodas LIKE 'grupes_main.pg_kodas%') as pristKaina
FROM grupes_main
WHERE grupes_main.level = 1
and grupes_main.name <> ''
In LIKE clause I want automatically get selected grupes_main column pg_kodas, but in this query it always returns 0, where is mistake in LIKE function? thx
SELECT id, name,
(
SELECT COUNT(*)
FROM prekes_main
WHERE prekes_main.pristKaina = 1
AND prekes_main.pg_kodas LIKE CONCAT(grupes_main.pg_kodas, '%')
) pristKaina
FROM grupes_main
WHERE grupes_main.level = 1
AND grupes_main.name <> ''