我有这样的SQL查询:

SELECT COUNT(*) AS count_value FROM submissions WHERE username = (
  SELECT username FROM submissions WHERE id = '1'
) AND number = (
  SELECT number FROM submissions WHERE id = '1'
) AND tstmp < (
  SELECT tstmp FROM submissions WHERE id = '1'
);


请注意,我如何使用此查询查找具有相似列值但时间戳值小于行号1的所有行。

这对我有用,但是我想知道,有没有办法将三个子查询合并为一个?他们都从同一张表中选择信息,因此我认为这是可能的,但是我不知道如何去做。

最佳答案

我认为您可以将子查询合并为一个并将其用作联接中的派生表。请尝试以下方法:

SELECT COUNT(*) AS count_value
FROM submissions s
JOIN (
    SELECT username, number, tstmp
    FROM submissions WHERE id = 1
) o ON s.number = o.number AND s.username = o.username AND s.tstmp < o.tstmp

10-04 18:29