Mysql查询没有按顺序获取数据

时间:2014-04-03 06:39:50

标签: mysql

我正在尝试使用左连接来获取数据。我的表格如下所示:

表1:

========================
     id   |   name
========================
      1   |   Amit
========================
      2   |   Manzoor
========================
      3   |   Atik
========================
      4   |   Sharif

表2:

===========================================
  t2_id  |    Date    | table1_id  |   status
===========================================
   1  | 2014-03-03 |   1        |   1
===========================================
   2  | 2014-03-04 |   2        |   1
===========================================
   3  | 2014-03-05 |   3        |  1 

我的查询如下:

SELECT * FROM table1 t1 LEFT JOIN table2 t2 ON t1.id=t1.table1_id ORDER BY status DESC

如果今天的日期与上述表格2的日期相符,那么我需要的数据如下所示

  id   |    name   |    t2_id     |    date    | table1_id  |   status
======================================================================
   1   |   Amit    |     1        | 2014-03-03 |   1        |   1
======================================================================
   2   |   Manzoor |     2        | 2014-03-04 |   2        |   1
======================================================================
   3   |   Atik    |     3        | 2014-03-05 |   3        |   1 
======================================================================
    4   |   Sharif |     NULL     | NULL       |   NULL     |  NULL

任何想法?

3 个答案:

答案 0 :(得分:1)

试试这个,

ORDER BY status IS NULL, status DESC

此语句status IS NULL将返回1表示true,0表示false表示,因此按升序排序会使NON-NULL首先出现在列表中。

答案 1 :(得分:0)

如果您希望按照所示排序,则应ORDER BY id。如果您希望按ID排序,然后按状态排序,则可以按多列排序:ORDER BY id, status

如果您想按日期排序,但将NULL值放在底部,那么:ORDER BY date IS NULL, date

答案 2 :(得分:0)

试试这个:

SELECT * FROM
(SELECT * FROM table1 t1 LEFT JOIN 
table2 t2 ON t1.id=t2.table1_id 
WHERE t2.Date IS NOT NULL
AND t2.Date = curdate()
ORDER BY t2.status DESC) T1

UNION ALL

SELECT * FROM
(SELECT *
FROM table1 t1 LEFT JOIN 
table2 t2 ON t1.id=t2.table1_id 
WHERE t2.Date IS NOT NULL 
      AND t2.Date <> curdate()
ORDER BY t2.Date ASC, t2.status DESC) T

UNION ALL

SELECT *
FROM table1 t1 LEFT JOIN 
table2 t2 ON t1.id=t2.table1_id 
WHERE t2.Date IS NULL

<强>解释

如果date字段为not null,则会选择所有记录,并按状态顺序选择当前日期

如果date字段为not null当前日期为date,则会显示记录。

UNION,其中date字段为null

请参阅SQL Fiddle中的结果。