sql語句之連表查詢
阿新 • • 發佈:2018-10-13
value 語句 varchar HERE use har not in uniq web
學習鏈接:https://blog.csdn.net/qq_43119297/article/details/82559687
1:創建book表,並插入數據
CREATE TABLE book( bookID VARCHAR(20) PRIMARY KEY , bookName VARCHAR(50) DEFAULT NULL ); INSERT INTO book VALUES (1,‘java基礎‘), (2,‘javaweb‘), (3,‘JDBC‘), (4,‘HTML高級‘);
2:創建loan表
CREATE TABLE loan( uid INT, bookID VARCHAR(32), lnum INT, PRIMARY KEY(uid,bookID) ); INSERT INTO loan VALUES (1,1,8), (2,4,2), (3,3,3), (4,2,7), (5,1,1), (2,3,10), (2,2,3), (3,1,5);
3.創建user表,並插入數據
CREATE TABLE USER( uid INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(20) UNIQUE, age INT, sex VARCHAR(2) ); INSERT INTO USER VALUES (NULL,‘周瑜‘,22,‘男‘), (NULL,‘小喬‘,18,‘女‘), (NULL,‘甄宓‘,23,‘女‘), (NULL,‘曹操‘,30,‘男‘), (NULL,‘貂蟬‘,26,‘女‘);
4,問題
– 1.查詢年齡小於 25的學生姓名、學生年齡 – 2.查詢年齡在18-22之間(包含18和22)的學生信息 –3. 統計學生表中男女的數量分別是多少 – 4.查詢學生的總人數、平均年齡、最小年齡 – 5.查詢借閱過圖書的每個學生ID借閱的總次數 – 6.查詢圖書名稱包含”java”的圖書數量 –7. 查詢借閱總次數大於50的學生學號 –8. 查詢借閱了’HTML高級’的學生學號 –9. 查詢沒有借閱過圖書的學生學號、學生姓名 – 10.查詢借閱過’javaWeb’圖書的學生學號、借閱次數 – 11.查詢年齡比”周瑜”大的所有學生姓名、學生年齡 – 12.查詢年齡最大的學生ID、學生姓名,學生年齡 –13. 查詢借閱了圖書的學生姓名、借閱的不同圖書總數、借閱所有圖書總次 –14. 查詢被借閱的每本圖書的圖書名稱、借閱總次數 – 15.查詢借閱次數最多的圖書ID和借閱的總次數 ---------------------
5,答案
1: SELECT username,age FROM USER WHERE age<25; 2: SELECT username,age FROM USER WHERE age BETWEEN 18 AND 22; 3: SELECT sex,COUNT(username) 數量 FROM USER GROUP BY sex; 4: SELECT COUNT(uid) 總人數,AVG(age) 平均年齡,MIN(age) 最小年齡 FROM USER; 5: SELECT uid,COUNT(lnum)借閱次數 FROM loan GROUP BY uid; 6: SELECT SUM(b.`lnum`) 總數 FROM book a,loan b AND bookname LIKE "java%"; 7: SELECT uid FROM loan GROUP BY uid HAVING SUM(lnum)>5; 8: SELECT user.`uid` FROM book,USER,loan WHERE loan.`bookID`=book.`bookID` AND loan.`uid` =user.`uid` AND book.`bookName`=‘HTML高級‘; 9: SELECT user.`uid`,user.`username` FROM book,USER,loan WHERE loan.`bookID`=book.`bookID` AND loan.`uid` =user.`uid` AND book.`bookName`NOT IN (‘HTML高級‘,‘JDBC‘,‘javaweb‘,‘java基礎‘); --------------------- 10: SELECT user.`uid`,SUM(loan.`lnum`) 次數 FROM book,USER,loan WHERE loan.`bookID`=book.`bookID` AND loan.`uid` =user.`uid` AND book.`bookName`=‘javaWeb‘ GROUP BY book.`bookName`; 11: SELECT username,age WHERE username=‘周瑜‘) t WHERE a.`age`>t.b; 12: SELECT uid, username,age FROM USER a , (SELECT MAX(age) b FROM USER ) t WHERE a.`age`=t.b; 13: SELECT a.`username`,s.e 借閱的不同圖書總數,s.b 借閱所有圖書總次 FROM USER a,(SELECT d.`uid` k,SUM(d.`lnum`) e , COUNT(d.`bookID`) b FROM loan d GROUP BY uid ) s WHERE a.`uid`=s.k; 14: SELECT book.bookname 書名,n.v 借閱次數 FROM book,(SELECT bookid s,SUM(lnum) v FROM loan GROUP BY bookid) n WHERE n.s=book.`bookID`; 15: SELECT bookID,MAX(n.a) FROM (SELECT bookid,SUM(lnum) a FROM loan GROUP BY bookid) n;
sql語句之連表查詢