MySQL associated query

Keywords: Database P4 MySQL

Two tables
Table A is A public curriculum with two fields, i.e. id and pro name. There are about five courses, and each of them should go to
Table B is the association table of user and course reminders. It has four fields: ID, pro ID, user ID and tip time, which respectively represent ID, course ID, user ID and reminder class time. Reminder class time cannot be empty, and not all courses need to add reminders
For example, there are 5 courses to be taught, as long as 3 courses have added reminders, so table B has only three records
A table data

 DROP TABLE IF EXISTS `A`;
CREATE TABLE `A` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `pro_name` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4;

 
INSERT INTO `A` VALUES ('1', 'p1');
INSERT INTO `A` VALUES ('2', 'p2');
INSERT INTO `A` VALUES ('3', 'p3');
INSERT INTO `A` VALUES ('4', 'p4');

B table data

DROP TABLE IF EXISTS `B`;
CREATE TABLE `B` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `pro_id` int(11) DEFAULT NULL,
  `user_id` int(11) DEFAULT NULL,
  `tip_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;

 
INSERT INTO `B` VALUES ('1', '3', '1', '2019-04-15 15:24:27');
INSERT INTO `B` VALUES ('2', '4', '1', '2019-04-16 15:24:39');
INSERT INTO `B` VALUES ('3', '5', '1', '2019-04-17 15:24:48');

The requirement is: sort the course schedule according to the reminder course time
First of all, think of external connections

select  
A.* ,B.*
from A LEFT 
JOIN B on A.id =B.pro_id AND B.user_id =1
order by B.tip_time DESC ,A.id DESC

Remember to add B. user? Id = 1, because the reminder table is not used by one person in practice

Query results

mysql> select  
A.* ,B.*
from A LEFT JOIN B on A.id =B.pro_id AND B.user_id =1
order by B.tip_time DESC ,A.id DESC;
+----+----------+------+--------+---------+---------------------+
| id | pro_name | id   | pro_id | user_id | tip_time            |
+----+----------+------+--------+---------+---------------------+
|  5 | p5       |    3 |      5 |       1 | 2019-04-17 15:24:48 |
|  4 | p4       |    2 |      4 |       1 | 2019-04-16 15:24:39 |
|  3 | p3       |    1 |      3 |       1 | 2019-04-15 15:24:27 |
|  2 | p2       | NULL | NULL   | NULL    | NULL                |
|  1 | p1       | NULL | NULL   | NULL    | NULL                |
+----+----------+------+--------+---------+---------------------+

Posted by ReD_BeReT on Sun, 24 Nov 2019 11:09:53 -0800