查询的WHERE语句为@variable

时间:2017-01-27 14:34:27

标签: mysql variables

我有一个查询,我想将一个变量插入到WHERE语句中。

WHERE @Variable

我尝试了以下(简化),但它似乎无效。

注意:我在这里没有包含连接元素,试图在提出问题之前自己解决这个问题。

SET @id := x;
SET @n := (SELECT COUNT(*) FROM Table2 WHERE id=@id);
SET @Variable := (
(
Table1.Column1=(SELECT Column1 FROM Table2 WHERE id=@id LIMIT 1 OFFSET 0)
AND Table1.Column2=(SELECT Column2 FROM Table2 WHERE id=@id LIMIT 1 OFFSET 0)
AND Table1.Column3=(SELECT Column3 FROM Table2 WHERE id=@id LIMIT 1 OFFSET 0)
)
.........
OR
(
Table1.Column1=(SELECT Column1 FROM Table 2 WHERE id=@id LIMIT 1 OFFSET @n)
AND Table1.Column2=(SELECT Column2 FROM Table2 WHERE id=@id LIMIT 1 OFFSET @n)
AND Table1.Column3=(SELECT Column3 FROM Table2 WHERE id=@id LIMIT 1 OFFSET @n)
)
)
;


SELECT Table1.Column1, Table1.Column2, Table1.Column3, Table2.Column1, Table2.Column2, Table2.Column3 
FROM Table1, Table2
WHERE
@Variable
;

1 个答案:

答案 0 :(得分:0)

所以这个:

SET @IDNumber := 21;
SELECT Players.PlayerID, COUNT(*) AS Games, SUM(Games.Points) 
FROM Teams, Players, Games

WHERE 
Teams.PlayerID=Players.PlayerID
AND
Games.Game=Teams.Game
AND
Games.Team=Teams.Team
AND
Games.GameDate=Teams.GameDate
AND
(
Games.Game= ANY (SELECT Game FROM Teams WHERE PlayerID=@IDNumber)
AND
Games.Team= ANY (SELECT Team FROM Teams WHERE PlayerID=@IDNumber)
AND
Games.GameDate= ANY (SELECT GameDate FROM Teams WHERE PlayerID=@IDNumber)
)

GROUP BY Teams.PlayerID
ORDER BY Games DESC
;

创建此:

+----------+-------+-------------------+
| PlayerID | Games | SUM(Games.Points) |
+----------+-------+-------------------+
|       15 |     8 |                10 |
|       21 |     8 |                10 |
|        8 |     8 |                10 |
|       14 |     6 |                 7 |
|        5 |     6 |                 7 |
|       19 |     5 |                 6 |
|       11 |     5 |                 7 |
|       12 |     3 |                 4 |
|       10 |     3 |                 3 |
|        4 |     2 |                 3 |
+----------+-------+-------------------+
10 rows in set (0.01 sec)

这正是我所寻找的。