如何在mysql中进行一些查询

mkshixfv  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(281)


这是我的作业,我正在找。总共17个问题。我不能回答5个问题,但我正在努力,努力。。
列出每个学生读的书的数量。但旁边那些不读书的人写0。
找到读得最多的书。
列出从来没有翻过书的学生。
按书号升序列出书号、书名和借阅次数。5列出所收图书的书号、借阅次数(未借阅图书旁写零“0”)。
1) 从student s left join process p on s.stnno=p.stnno left join book b on b.bookno=p.bookno group by s.stnname,s.stnsurname中选择s.stnname,s.stnsurname,sum(b.bookname);假

fnatzsnv

fnatzsnv1#

考虑以下几点。我故意简化了设计,它的效果是禁止一个学生可能借同一本书两次。。。

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 |
+---------+------------------------+----------------+

相关问题