我有一个MySQL查询:
SELECT *
FROM t1
WHERE ABS(TIMESTAMPDIFF(MINUTE, ts, (SELECT ts FROM t1 WHERE id=1 AND c1 < 5))) < 3
AND id=1
子查询返回4行,因此无法执行查询。我已将其更改为使用join:
SELECT *
FROM t1 a INNER JOIN t1 b
ON a.id=b.id AND b.id=1 AND c1<5
WHERE ABS(TIMESTAMP(MINUTE, a.ts, b.ts))<3;
我有两个问题: 1.我转换(从子查询到加入)对吗? 2.无论如何要修复我的子查询?
感谢。
答案 0 :(得分:1)
1。
这是无效的,因为你必须为所有字段添加前缀(可能是拼写错误),否则你会出现歧义错误。和其他拼写错误(TIMESTAMP
而不是TIMESTAMPDIFF
)
顺便说一句,在您的情况下,您可以将谓词条件放在where子句中,而不是在连接中。
SELECT a.*
FROM t1 a
INNER JOIN t1 b
ON a.id=b.id
WHERE a.id = 1
AND b.c1 < 5
AND ABS(TIMESTAMPDIFF(MINUTE, a.ts, b.ts))<3;
2。 也许EXISTS条款可以完成这项工作。
SELECT a.*
FROM t1 a
WHERE a.id = 1
AND EXISTS
(SELECT NULL FROM t1 b
WHERE b.id = a.id
AND b.c1 < 5
AND TIMESTAMPDIFF(MINUTE, a.ts, b.ts) < 3)
答案 1 :(得分:1)
您可以在此选择查询中使用不同的键
SELECT distinct a.* FROM t1 a WHERE a.id = 1 AND EXISTS (SELECT NULL FROM t1 b WHERE b.id = a.id AND b.c1 < 5
AND TIMESTAMPDIFF(MINUTE,a.ts,b.ts)&lt; 3)