13 Subqueries

1. Subqueries using the IN keyword
Question: Query the score information of games whose game type is "chess and card"
Game type information is not included in the game score table
Idea 1: Use join query
Idea 2: Carry out in two steps, first find the numbers of all "chess and card" games, and complete the query based on this group of numbers
Idea 2 Example 1:

SELECT * FROM scores
where gno IN #Query basis
(SELECT gno from games WHERE gtype = "chess and cards") #query clause

Note: Subqueries are generally not written as SELECT * FROM...
Idea 2 Example 2: Query the QQ of players who did not participate in the No. 5 game

SELECT user_qq FROM scores
where user_qq NOT IN
(SELECT user_qq from scores WHERE GNO = 5)
The above spelling is wrong: the score table does not contain the QQ of all players, but only the players who have played the game. Players who did not participate in the game are naturally not in the scores table.
the following
SELECT user_qq FROM users
LEFT JOIN scores ON users.user_qq = scores.user_qq
where user_qq NOT IN
(SELECT user_qq from users WHERE GNO = 5)

Idea 2 Example 3: Query players QQ and players GNO who have not participated in the No. 5 game

SELECT users.user_qq ,GNO FROM users
LEFT JOIN scores ON users.user_qq = scores.user_qq
where users.user_qq NOT IN
(SELECT scores.user_qq from scores WHERE GNO = 5)

Note: When there is no GNO field in the users table, the field GNO of the scores table needs to be externally connected.
2.使用EXISTS关键字的子查询
示例:如果存在昵称为“dang”,则查询分数表中的数据。

SELECT * FROM scores
WHERE EXISTS
(SELECT * FROM users WHERE user_name = 'dang')

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324852405&siteId=291194637