如何做一些MYSQL查询

时间:2019-01-06 09:12:53

标签: mysql sql

enter image description here

这是我的作业,正在搜索。总共17个问题。我无法提出5个问题,但我正在尝试....

  1. 列出每个学生阅读的书籍数量。但是,在那些不读书的人旁边写上0。
  2. 找到最常阅读的书。
  3. 列出从未借书的学生。
  4. 根据书号列出书号,名称和按升序借书的次数。 5列出接收到的书的书号,借书的次数(在未借书的旁边写零“ 0”)。

1)从学生的s.stnno = p.stnno的LEFT JOIN流程p上选择学生的s.stnname,s.stnsurname,sum(b.bookname)b.bookno = p.bookno GROUP BY s .stnname,s.stnsurname; 假

1 个答案:

答案 0 :(得分:0)

请考虑以下内容。我故意简化了设计,从而避免了学生可能两次借用同一本书的可能性……

DROP TABLE IF EXISTS student_book;

CREATE TABLE student_book
(student_id INT NOT NULL
,book_id INT NOT NULL
,PRIMARY KEY(student_id,book_id)
);

DROP TABLE IF EXISTS student;

CREATE TABLE student
(student_id SERIAL NOT NULL PRIMARY KEY
,student_name VARCHAR(30) NOT NULL
);

DROP TABLE IF EXISTS book;

CREATE TABLE book
(book_id SERIAL NOT NULL PRIMARY KEY
,book_title VARCHAR(30) NOT NULL
);

INSERT INTO student VALUES 
(1,'John'),
(2,'Paul'),
(3,'George'),
(4,'Ringo');

INSERT INTO book VALUES
(101,'In Search of Lost Time'),
(102,'Don Quixote'),
(103,'Ulysses'),
(104,'The Great Gatsby');

INSERT INTO student_book VALUES 
(1,101),
(1,102),
(2,102),
(3,101),
(3,102),
(3,103);


1. 

   SELECT s.*
        , COUNT(sb.book_id) total 
     FROM student s 
     LEFT 
     JOIN student_book sb 
       ON sb.student_id = s.student_id 
    GROUP 
       BY s.student_id;
+------------+--------------+-------+
| student_id | student_name | total |
+------------+--------------+-------+
|          1 | John         |     2 |
|          2 | Paul         |     1 |
|          3 | George       |     3 |
|          4 | Ringo        |     0 |
+------------+--------------+-------+

2. -- This solution ignores the possibility of ties

SELECT b.* 
  FROM book b 
  JOIN student_book sb 
    ON sb.book_id = b.book_id 
 GROUP 
    BY book_id 
 ORDER 
    BY COUNT(*) DESC 
 LIMIT 1;
+---------+-------------+
| book_id | book_title  |
+---------+-------------+
|     102 | Don Quixote |
+---------+-------------+

3. 

SELECT s.* 
  FROM student s 
  LEFT 
  JOIN student_book sb 
    ON sb.student_id = s.student_id 
 WHERE sb.book_id IS NULL;
+------------+--------------+
| student_id | student_name |
+------------+--------------+
|          4 | Ringo        |
+------------+--------------+

4. 

SELECT b.*
     , COUNT(sb.student_id) times_borrowed -- actually 'borrowed by how many distinct students!!
  FROM book b 
  LEFT 
  JOIN student_book sb  
    ON sb.book_id = b.book_id 
 GROUP 
    BY b.book_id 
 ORDER 
    BY b.book_id;
+---------+------------------------+----------------+
| book_id | book_title             | times_borrowed |
+---------+------------------------+----------------+
|     101 | In Search of Lost Time |              2 |
|     102 | Don Quixote            |              3 |
|     103 | Ulysses                |              1 |
|     104 | The Great Gatsby       |              0 |
+---------+------------------------+----------------+