如何在 SQL 中进行嵌套查询

How to do Nested Queries in SQL

我正在努力学习 SQL,虽然我正在慢慢学习如何查询数据,但我一直停留在查询查询结果上。举个例子

我想要一个 SQL 语句来做两件事。假设我有 2 个 table 如下所示(table 1 从堆栈溢出的另一个例子中借用)

Table 1:

ID  game   point  time
1    x      5     7:00
1    z      4     11:00
2    y      6     9:00
3    x      2     2:00
3    y      5     4:00
3    z      8     6:00
4    k      0     8:00    

Table 2:

id  tv chan
1    cab  
2    trop  
3    start   
4    cab  

我要做的第一件事是合并这些 table 中的某些列。我知道我可以 select 这些列并对 ID

进行内部连接

然而,我想做的第二件事是删除所有具有分值 0 的行,然后仅具有具有最低分值的不同游戏名称的行。所以我希望最后的 table 看起来像这样

id  game   point   tv chan    
1    z      4       cab
2    y      5       trop
3    x      2       start

谢谢

您可以将连接与按 id 和游戏分组的子查询一起使用以获得最小分

    select t1.id, t1.game. t1.point, t2 `tv chan`
    from (
        select id, game,  min(point) point
        from table1
        where point > 0
        group by id, game
    ) t1 
    inner join table2 t2 on t1.id = t2.id

您可以尝试这样的操作:

SELECT t1.ID, 
       t1.game, 
       t1.point, 
       t2.tv_chan 
FROM Table1 AS t1
INNER JOIN Table2 AS t2 ON t2.id = t1.id 
INNER JOIN (SELECT t11.game, MIN(t11.point) AS min_point  
            FROM Table1 AS t11 
            WHERE t11.point != 0 
            GROUP BY t11.game
           ) AS t3 ON t3.game = t1.game
                      AND t3.min_point = t1.point 
WHERE t1.point != 0