0

我有一个 MySQL 查询:

SELECT * 
FROM t1
WHERE ABS(TIMESTAMPDIFF(MINUTE, ts, (SELECT ts FROM t1 WHERE id=1 AND c1 < 5))) < 3
AND id=1

子查询返回 4 行,因此无法执行查询。我已将其更改为使用加入:

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;

我有 2 个问题: 1. 我转换(从子查询到加入)对吗?2.无论如何要修复我的子查询?

谢谢。

4

2 回答 2

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) < 3)

于 2012-10-29T08:27:32.030 回答
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)
于 2012-10-29T07:59:19.133 回答