使用联接表Mysql按同一列排序

时间:2018-11-16 11:09:25

标签: mysql

我有两个桌子:母亲和孩子。每个母亲都有一个或多个孩子。

母亲:

id | name  | age 
1  | name1 | 30
2  | name2 | 40 
3  | name3 | 35 

孩子:

id | name   | age | id_mother
1  | child1 | 15  | 1 
2  | child2 | 10  | 2

我想要的结果是按ASC年龄排序母亲订单,按其asc年龄孩子排序。

编辑(通过评论):我只想按最小孩子年龄(如果有孩子的话)排序,然后按母亲年龄排序。

例如:

id | name  | age 
2  | name2 | 40 
1  | name1 | 30 
3  | name3 | 35

我尝试了此sql:

SELECT * 
FROM mother m
ORDER BY m.age asc , (SELECT MIN(age) FROM child c WHERE c.id_mother == m.id)

但是它按年龄分给妈妈吗?

2 个答案:

答案 0 :(得分:0)

我认为您只是想按最小儿童年龄(如果有孩子的话)排序,然后按母亲年龄排序。

  • 在相关子查询中,您可以从母亲的孩子(如果存在)中获得最小年龄。
  • ORDER BY中,我们将使用IS NOT NULL将案件放在最低儿童年龄值的前面。

尝试:

SELECT
  m.*, 
  (SELECT MIN(c.age) 
   FROM child AS c
   WHERE c.id_mother = m.id) AS min_child_age 
FROM mother AS m 
ORDER BY 
  min_child_age IS NOT NULL DESC, 
  min_child_age ASC, 
  m.age ASC 

模式(MySQL v5.7)

create table mother 
(id int, name varchar(8), age int);

insert into mother values
(1, 'name1', 30), (2, 'name2', 40), (3, 'name3', 35); 


create table child
(id int , name varchar(8), age int, id_mother int);

insert into child values 
(1  , 'child1' , 15  , 1 ),
(2  , 'child2' , 10  , 2);

结果

| id  | name  | age | min_child_age |
| --- | ----- | --- | ------------- |
| 2   | name2 | 40  | 10            |
| 1   | name1 | 30  | 15            |
| 3   | name3 | 35  |               |

View on DB Fiddle

答案 1 :(得分:0)

try using this method :
select * from mother;
+----+-------+-----+
| id | name  | age |
+----+-------+-----+
|  1 | name1 |  30 |
|  2 | name2 |  40 |
|  3 | name3 |  35 |
+----+-------+-----+

select * from child;
+----+--------+-----+-----------+
| id | name   | age | id_mother |
+----+--------+-----+-----------+
|  1 | child1 |  15 |         1 |
|  2 | child2 |  10 |         2 |
+----+--------+-----+-----------+


SELECT mo1. * , (SELECT MIN( ch1.age ) FROM child AS ch1 WHERE ch1.id_mother = mo1.id) AS child_age FROM mother AS mo1 ORDER BY child_age IS NOT NULL DESC , child_age ASC ;
+----+-------+-----+-----------+
| id | name  | age | child_age |
+----+-------+-----+-----------+
|  2 | name2 |  40 |        10 |
|  1 | name1 |  30 |        15 |
|  3 | name3 |  35 |      NULL |
+----+-------+-----+-----------+