E
E
enchikiben2011-01-18 15:06:35
MySQL
enchikiben, 2011-01-18 15:06:35

union & ORDER BY?

Good time of the day!
There is a table:

idnamegood_namepayment
oneaaatrue
2bbbpayment
3ccctrue

It is necessary to select paid companies and sort them by product (good_name), then unpaid ones go, and they must be sorted by company name (name).
Tried with union:
(SELECT * FROM `table` WHERE `payment`=&quot;true&quot; ORDER BY `good_name` ASC )<br/>
union<br/>
(SELECT * FROM `table` WHERE `payment`=&quot;false&quot; ORDER BY `name` ASC )<br/>

How can this perversion be realized?..
P.S. Thank you corrected the errors.

Answer the question

In order to leave comments, you need to log in

6 answer(s)
E
Eugene, 2011-01-18
@Agent_J

can it be easier

SELECT 
    *,
    IF(`payment`='true', `good_name`, `name`) prior
FROM `table` 
WHERE 
    `payment`="true" 
ORDER BY payment, prior

E
Eugene, 2011-01-18
@Agent_J

SELECT * FROM (
   SELECT * FROM `table` WHERE `payment`=="true" ORDER BY `good_name` ASC
) a
UNION
select * from (
   SELECT * FROM `table` WHERE `payment`=="false" ORDER BY `name` ASC 
) b

this will work, but you are right - this is a perversion

A
Antelle, 2011-01-18
@Antelle

SELECT * FROM test ORDER BY payment, CASE WHEN payment = 1 THEN good_name ELSE NAME end

C
cuprum, 2011-01-18
@cuprum

SELECT * FROM `table` ORDER BY `payment` DESC, `good_name` ASC

X
XaBoK, 2011-01-18
@XaBoK

I can’t vouch for the syntax, but the meaning is simple - do Select from a generalized table using an additional field:

SELECT   id, name, good_name, payment
FROM     (SELECT   TOP (100) PERCENT id, name, good_name, payment, good_name AS ordr
            FROM     temp
            WHERE   (payment = 1)
            UNION
            SELECT   TOP (100) PERCENT id, name, good_name, payment, name AS ordr
            FROM     temp AS temp_1
            WHERE   (payment = 0)) AS t2_1
ORDER BY payment DESC, ordr
* This source code was highlighted with Source Code Highlighter.

G
GeniyZ, 2011-01-18
@GeniyZ

and in which DBMS can/should one write WHERE `payment`=="true" instead of IS TRUE and even doubled equals? Please do not kick me - except for ORACLE, I have practically not seen anything over the past couple of years and I try to use ANSI as much as possible.
my version: SELECT t.*, decode(payment, true, good_name, name) as ord FROM table as t ORDER BY ord
is no better than IF/CASE

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question