使用INNER JOIN

时间:2018-04-26 17:46:41

标签: mysql

如何将WHERE子句与table_1中的字段一起使用,并将INNER JOIN连接到table_2。像下面的东西。

SELECT t1.result, t1.result_date
    FROM outcomes t1 
    WHERE t1.status = 'finished'
    INNER JOIN games t2
      ON t1.game_id = t2.game_id
    WHERE t2.closing_time < NOW();

以下是样本表:

游戏桌

-------------------------------------------------------
game_id   name      start_time               closing_time
--------------------------------------------------------
1          aaa     2018-04-25 16:00:45     2018-04-25 16:30:45
2          bbb     2018-04-25 17:00:45     2018-04-25 17:30:45
3          ccc     2018-04-25 18:00:45     2018-04-25 18:30:45
---------------------------------------------------------------

结果表

----------------------------------------------------------------------
id   game_id    result      round    result_date          status
----------------------------------------------------------------------
1      1       2,4,6       1        2018-04-25 16:15:45  finished
2      1       4,5,3       2        2018-04-25 16:35:45  canceled
3      2       1,2,4       1        2018-04-25 17:15:45  finished
4      2       5,2,4       2        2018-04-25 17:30:45  canceled
5      3       1,2,3       1        2018-04-25 18:15:45  finished
6      3       2,2,5       2        2018-04-25 18:30:45  to-be-confirmed
---------------------------------------------------------------------

假设当前时间是2018-04-25 18:13,我的预期输出是:

2,4,6        2018-04-25 16:15:45
1,2,4        2018-04-25 17:15:45 

对应于id等于1的行,3对应于结果表

2 个答案:

答案 0 :(得分:3)

只能有一个WHERE子句,它必须在所有FROMJOIN子句之后。将条件与AND结合使用。

SELECT t1.result, t1.result_date
FROM outcomes t1 
INNER JOIN games t2
  ON t1.game_id = t2.game_id
WHERE t2.closing_time < NOW())
  AND t1.status = 'finished'

答案 1 :(得分:1)

我不知道我的问题是否正确,但我认为你正在寻找类似的东西

SELECT t1.result, t1.result_date
        FROM outcomes t1 
        INNER JOIN games t2
          ON t1.game_id = t2.game_id
        WHERE t2.closing_time < NOW() AND t1.status = 'finished';