1选择查询按2列排序?

时间:2016-11-24 10:27:55

标签: php mysql subquery

我想知道是否可以通过一个查询实现某些目标。这是我的表结构知道thay(id,id_attached)是一个独特的索引

id      id_attached     name
20      0               Name of row 1
21      0               Name of row 2
22      20              Name of row 3
23      20              Name of row 4
15      20              Name of row 5

是否可以使用一个查询按此顺序选择行。我需要使用GROUP BY ID,但同时我需要为行2分别设置2行?

20  Name of row 1
  15   Name of row 5
  22   Name of row 3
  23   Name of row 4
21  Name of row 2

1 个答案:

答案 0 :(得分:2)

您可以这样排序:

SELECT *
from my_table
ORDER BY IF(`id_attached` is NULL, id, `id_attached`),id;

并为你提出第二个问题:

SELECT * from my_table ORDER BY IF(`id_attached` = 0, id, `id_attached`),id;

结果现在在你的问题中是一样的。这不正确请再次问我,抱歉

<强>示例

mysql> select * from my_table;
+------+-------------+---------------+
| id   | id_attached | name          |
+------+-------------+---------------+
|    1 |        NULL | Name of row 1 |
|    2 |        NULL | Name of row 2 |
|    3 |           1 | Name of row 3 |
|    4 |           1 | Name of row 4 |
+------+-------------+---------------+
4 rows in set (0,00 sec)

mysql>
mysql>
mysql> SELECT * from my_table
    -> ORDER BY IF(`id_attached` is NULL, id, `id_attached`),id;
+------+-------------+---------------+
| id   | id_attached | name          |
+------+-------------+---------------+
|    1 |        NULL | Name of row 1 |
|    3 |           1 | Name of row 3 |
|    4 |           1 | Name of row 4 |
|    2 |        NULL | Name of row 2 |
+------+-------------+---------------+
4 rows in set (0,00 sec)

mysql>

带有子订单的示例

SELECT * from my_table m ORDER BY IF(id_attached = 0, id, id_attached+0.1),id;

使用新字段的示例

这将自动更新新字段。仅当ID不是AUTO_INC

时才有效
ALTER TABLE my_table
add COLUMN myorder INT GENERATED ALWAYS
AS (
    IF(`id_attached` = 0, id<<1, (`id_attached`<<1) +1) 
    ) STORED
;

ALTER TABLE my_table ADD INDEX idx_myorder (myorder);

<强>结果

mysql> select * from my_table;
+----+-------------+----------------+---------+
| id | id_attached | name           | myorder |
+----+-------------+----------------+---------+
| 15 |          20 |  Name of row 5 |      41 |
| 20 |           0 |  Name of row 1 |      40 |
| 21 |           0 |  Name of row 2 |      42 |
| 22 |          20 |  Name of row 3 |      41 |
| 23 |          20 |  Name of row 4 |      41 |
+----+-------------+----------------+---------+
5 rows in set (0,00 sec)

mysql>