简体   繁体   English

如何从 mysql 中的当前行获取特定列值?

[英]How to get a specific column value from current row in mysql?

How can I get the value of a specific column in the current row?如何获取当前行中特定列的值? Let's say we have a table "games" with columns "gameid" and "game_type".假设我们有一个表“games”,其中包含“gameid”和“game_type”列。 Each game has multiple winners (one user can win any number of times).每场比赛都有多个获胜者(一个用户可以赢得任意次数)。 Now let's assume we have another table "game_winners" which keeps track of all the game-winners and has "gameid", "userid".现在让我们假设我们有另一个表“game_winners”,它跟踪所有的游戏获胜者并且有“gameid”、“userid”。 What I want to achieve is get the number of unique winners in a particular game.我想要实现的是获得特定游戏中唯一获胜者的数量。 The query I need would look something like this:我需要的查询看起来像这样:

select gameid, game_type, (
  select count(distinct(userid)) 
  from games 
  join winners 
  where gameid = {gameid of current row}
) as game_winners 
from games 
join winners 

I'm not sure how to get the gameid from the current row and pass it into the where clause.我不确定如何从当前行获取游戏 ID 并将其传递给 where 子句。

Any help is very much appreciated.很感谢任何形式的帮助。

You can either use a correlated subquery aggregating:您可以使用相关的子查询聚合:

SELECT g.gameid,
       g.game_type,
       (SELECT count(DISTINCT w.userid)
               FROM winners w
               WHERE w.gameid = g.gameid) AS game_winners
       FROM games g;

Or join and then aggregate:或者加入然后聚合:

SELECT g.gameid,
       g.game_type,
       count(DISTINCT w.userid) AS game_winners
       FROM games g
            LEFT JOIN winners w
                      ON w.gameid = g.gameid
       GROUP BY g.gameid,
                g.game_type;

And BTW, DISTINCT is not a function, the parenthesis aren't needed.顺便说一句, DISTINCT不是 function,不需要括号。

This would give you expected result:这会给你预期的结果:

SELECT
    g.gameid,
    g.game_type,
    count(DISTINCT gw.user_id) as game_winners
FROM
    `game` g
    LEFT JOIN winners gw ON gw.game_id = g.gameid
GROUP BY
    g.gameid;

If you want to get result of single game, just add: (replace '1' with your ID)如果您想获得单场比赛的结果,只需添加:(将'1'替换为您的ID)

WHERE g.gameid = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM