mysql—选择行数等于其他表中某个值的行

4zcjmb1e  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(392)

我有两张table:游戏和任务
游戏如下:

| step | manualTaskCounter | autoTaskCounter | (and other)
----------------------------------------------------------
|  1   |      3            | 1               | ...
----------------------------------------------------------

任务如下所示:

| id | taskType | taskContent |
-------------------------------
|  1 |    M     | abc         |
|  2 |    M     | cde         |
|  3 |    A     | efg         |
|  4 |    M     | jpq         |

因为任务同时包含手动(使用m tasktype)和自动(a)任务,所以我要选择它们。我的api包含两个变量:mtaskcounter和ataskcounter。例如,如果mtaskcounter=3,我想从tasks中选择manualtask类型的第三行。因为它实际上是id=4的行,所以我不能在where子句中使用id。
我已经取得的成就是:

SELECT
    id,
    taskType,
    taskContent,
    (@row:=@row + 1) as rowNumber,
    g.manualTaskCounter as mTaskCounter
FROM
    tasks t,
    (SELECT @ROW:=0) AS r,
    (SELECT manualTaskCounter FROM game) AS g
WHERE
    g.manualTaskCounter = rowNumber

这表示where子句中的“未知列‘rownumber’”
我还尝试使用左连接:

SELECT
    id,
    taskType,
    taskContent,
    (@row:=@row + 1) as rowNumber,
    g.manualTaskCounter as mTaskCounter
FROM
    tasks t,
    (SELECT @ROW:=0) AS r
LEFT JOIN
    `game` g ON g.manualTaskCounter = rowNumber

同样的结果。我已经有一段时间没有每天使用mysql了,不知道如何修复它。我还想用手工任务和自动任务两个表来代替任务,这样就可以用共同的方法来解决问题 select taskContent from autoTasks a LEFT JOIN game ON a.id = game.autoTaskCounter

5lwkijsr

5lwkijsr1#

为了达到目标,首先需要为手动和自动任务生成派生表。接下来的查询将使这些表也增加行号:
带有手动任务的表

SELECT
    t.id,
    t.taskType,
    t.taskContent,
    (@row_num := @row_num + 1) AS rowNum
FROM
    tasks AS t
CROSS JOIN
    (SELECT @row_num := 0) AS r
WHERE
    taskType = 'M'

自动任务表

SELECT
    t.id,
    t.taskType,
    t.taskContent,
    (@row_num := @row_num + 1) AS rowNum
FROM
    tasks AS t
CROSS JOIN
    (SELECT @row_num := 0) AS r
WHERE
    taskType = 'A'

现在,您只需将这些派生表与 game 关于适当列的表:
使用 manualTaskCounter 领域

SELECT
    mTasks.*
FROM
    game AS g
INNER JOIN
    ( SELECT
          t.id,
          t.taskType,
          t.taskContent,
          (@row_num := @row_num + 1) AS rowNum
      FROM
          tasks AS t
      CROSS JOIN
          (SELECT @row_num := 0) AS r
      WHERE
           taskType = 'M' ) AS mTasks ON mTasks.rowNum = g.manualTaskCounter

使用 autoTaskCounter 领域

SELECT
    aTasks.*
FROM
    game AS g
INNER JOIN
    ( SELECT
          t.id,
          t.taskType,
          t.taskContent,
          (@row_num := @row_num + 1) AS rowNum
      FROM
          tasks AS t
      CROSS JOIN
          (SELECT @row_num := 0) AS r
      WHERE
           taskType = 'A' ) AS aTasks ON aTasks.rowNum = g.autoTaskCounter

查看下一个联机示例:
db小提琴示例

相关问题