如何将MySQL查询转换为事务SQL查询

时间:2018-08-14 18:59:26

标签: mysql sql-server

我有一个在MySQL中工作的查询。我需要使用TRANSACT SQL创建相同的结果。我无法弄清楚咒语。这是MySQL查询:

CREATE TEMPORARY TABLE tempo AS 
(SELECT master, MAX(nev) AS max 
 FROM accounts 
 WHERE where-clause 
 GROUP BY master 
 ORDER BY max DESC LIMIT 3);

SET @min = (SELECT MIN(max) FROM tempo);

SELECT * FROM accounts 
WHERE master IN (SELECT master FROM tempo) AND nev >= @min ORDER BY NEV DESC;

我们将向您提供帮助或说明指针

4 个答案:

答案 0 :(得分:0)

我从未使用过MySQL,但我认为这是您想要的:

DECLARE @min INT;

SELECT TOP 3
       master
     , MAX(nev) AS max
INTO #tempo
FROM accounts
WHERE WHERE-clause
GROUP BY master
ORDER BY max DESC;

SELECT @min = MIN(max)
FROM #tempo;

SELECT *
FROM accounts
WHERE master IN
      (
          SELECT master FROM #tempo
      )
      AND nev >= @min
ORDER BY NEV DESC;

答案 1 :(得分:0)

SELECT top 3 master, MAX(nev) AS max into #tempo FROM accounts WHERE where-clause GROUP BY master ORDER BY max DESC;

DECLARE @min NUMERIC(38);
SET @min = (SELECT MIN(max) FROM #tempo);

SELECT * FROM accounts WHERE master IN (SELECT master FROM #tempo) AND nev >= @min ORDER BY NEV DESC;

我会以这种方式翻译它。但是您不需要临时的。您可以编写一个查询来获得结果,这对于SQL引擎会更好。 希望对您有所帮助。

答案 2 :(得分:0)

类似这样的东西:

WITH tempo AS (
    SELECT TOP 3 master, 
        MAX(nev) AS max 
    FROM accounts 
    WHERE [WHERE-clause] 
    GROUP BY master 
    )

SELECT @min = MIN(max)
FROM tempo;

SELECT *
FROM accounts
WHERE master IN (
        SELECT master
        FROM tempo
        )
    AND nev >= @min
ORDER BY NEV DESC;

话虽这么说,可能有更好的方式编写此内容(例如SQL Server中的单个查询),但可以各自编写。

答案 3 :(得分:0)

我们可以使用CTE作为比临时表更好的选项,并且JOIN可能是IN()表达式的更好替代品,并且具有相同的结果:

WITH temp0 As (
  SELECT TOP 3 master, MAX(nev) AS max 
  FROM accounts 
  WHERE where-clause 
  GROUP BY master 
  ORDER BY MAX(nev) DESC 
)
SELECT a.* 
FROM accounts a 
INNER JOIN temp0 t ON t.master = a.master
WHERE a.nev >= (SELECT MIN(max) FROM temp0) 
ORDER BY a.NEV DESC;

这也是在最新版本的MySql中编写它的更好方法。