mysql 用表别名行替换搜索条件

sqougxex  于 2023-08-02  发布在  Mysql
关注(0)|答案(1)|浏览(100)

我有一个SQL查询如下:

SELECT * FROM results 
                WHERE (f_player1='O´Shea, John' OR f_player2='O´Shea, John')

字符串
我想动态地替换'O´Shea, John'与一组由其他球员的基础上,他们是否发挥。

SELECT player FROM
(
    SELECT f_player1 AS player FROM results WHERE DATE(f_datetime) = CURDATE()
    UNION 
    SELECT f_player2 AS player FROM results WHERE DATE(f_datetime) = CURDATE()
) x


这给了我一个5行(玩家)的列表。如何动态地合并所有5个播放器来替换原始字符串?
是通过连接吗?,临时变量?

qojgxg4l

qojgxg4l1#

连接看起来是这样的:

SELECT r.*
FROM results r
JOIN
(
  SELECT f_player1 AS player FROM results WHERE DATE(f_datetime) = CURDATE()
  UNION 
  SELECT f_player2 AS player FROM results WHERE DATE(f_datetime) = CURDATE()
) p ON p.player IN (r.f_player1, r.f_player2);

字符串
这将为您提供今天玩过的所有玩家的所有结果。
不过,我建议在这里使用EXISTS子句,因为您希望在某些行 * 存在 * 时选择行。

SELECT r.*
FROM results r
WHERE EXISTS
(
  SELECT NULL
  FROM results r2
  WHERE DATE(r2.f_datetime) = CURDATE()
  AND 
  (
    r2.f_player1 IN (r.f_player1, r.f_player2) 
     OR
    r2.f_player2 IN (r.f_player1, r.f_player2)
  )
);

相关问题