Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order the resulting rows based on multiple columns

I have to put down the lines that have two distinct fields with value = 0

Let me explain, all records that have stock_it=0 and stock_eu=0 must go to the bottom of the results

I have used this solution, however, it is not strictly correct because it puts down even rows that do not have both values = 0

$dati = mysql_query("
    SELECT      * 
    FROM        $tb_article
    ORDER BY
        FIELD($tb_art.article_status,'n') DESC, 
        FIELD($tb_art.article_stock_it,'0') ASC, 
        FIELD($tb_art.article_stock_eu,'0') ASC,  
        $tb_art.article_rank
");
  1. article_status=n indicates new products and they have to stay on top!
  2. Push to bottom all the article that have stock IT and stock EU = 0 (products not available)
  3. In the end, order the rest of the articles according to the rank assigned
like image 635
ActiveMedia Avatar asked Dec 13 '25 02:12

ActiveMedia


2 Answers

You can use the CASE statement in ORDER BY, like this:

SELECT      * 
FROM        $tb_article
ORDER BY
   CASE WHEN article_status = 'n' THEN 0
        WHEN article_stock_it = 0 THEN 100000
        WHEN article_stock_eu = 0 THEN 100000
        ELSE article_rank
   END 
like image 200
Aziz Shaikh Avatar answered Dec 15 '25 23:12

Aziz Shaikh


If you want to use ORDER BY FIELD : SQL Fiddle

MySQL 5.6 Schema Setup:

CREATE TABLE tb_article
(
    article_stock_it int,
    article_stock_eu int,
    article_status varchar(11),
    article_rank int
);

INSERT INTO tb_article VALUES
  (1, 1, 'n', 1)
, (0, 1, 'n', 1)
, (0, 0, 'n', 1)
, (1, 1, 'o', 1)
, (1, 1, 'o', 2);

Query 1:

SELECT      * 
    FROM        tb_article
    ORDER BY
        FIELD(tb_article.article_status,'n') DESC, 
        FIELD(
          IF(tb_article.article_stock_it = 0 AND tb_article.article_stock_eu = 0,'1','0')
          ,'0') DESC,
       tb_article.article_rank

Results:

| article_stock_it | article_stock_eu | article_status | article_rank |
|------------------|------------------|----------------|--------------|
|                1 |                1 |              n |            1 |
|                0 |                1 |              n |            1 |
|                0 |                0 |              n |            1 |
|                1 |                1 |              o |            1 |
|                1 |                1 |              o |            2 |
like image 42
Daniel E. Avatar answered Dec 16 '25 00:12

Daniel E.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!