在Metabase中连接两个具有不同列名的SQL表

时间:2018-04-21 12:54:40

标签: sql join metabase

我正在使用Metabase在我的数据库上提问。我试图加入两个表,其中相同的信息(用户ID)有两个不同的名称。我写的代码如下:

SELECT
    game_states.game_module AS game, count(*)
FROM
    game_states gs LEFT JOIN users u ON gs.user_id = u.id;
WHERE
    games_states.state = 'after_hands'
AND
    user.last_joined_stamp > now() - interval '30 days'
GROUP BY
    1
ORDER BY
    2 DESC

我一直收到以下错误: 错误:对表" game_states"的FROM子句条目的无效引用提示:也许您打算引用表别名" gs"。位置:127

1 个答案:

答案 0 :(得分:0)

定义表别名后,使用它!

SELECT gs.game_module AS game, count(*)
-------^
FROM game_states gs LEFT JOIN
     users u
     ON gs.user_id = u.id;
WHERE gs.state = 'after_hands' AND
------^
      u.last_joined_stamp > now() - interval '30 days'
------^
GROUP BY 1
ORDER BY 2 DESC;

顺便说一下,你可能打算:

SELECT gs.game_module AS game, count(u.id)
FROM game_states gs LEFT JOIN
     users u
     ON gs.user_id = u.id AND
        u.last_joined_stamp > now() - interval '30 days'
WHERE gs.state = 'after_hands' 
GROUP BY 1
ORDER BY 2 DESC;

您正在使用LEFT JOIN,因此可能希望包含所有匹配的游戏 - 即使那些没有匹配用户的游戏也是如此。如果是这样,请不要对u子句中的where进行过滤并计算匹配项,以便获得0