我在 SQL Server 中有一个SQL查询,就像这样
SELECT
CASE WHEN ROW_NUMBER() OVER(PARTITION BY _no ORDER BY _no asc) = 1 THEN
_no ELSE '' END
as row_no,
_no,
_name,
r._names
FROM
(
SELECT '1' as _no, 'vikas' as _name UNION ALL
SELECT '1', 'kratika' UNION ALL
SELECT '2', 'vikas' UNION ALL
SELECT '1', 'kratika kastwar'
) t
INNER JOIN
(
SELECT '1' as _nos, 'One' as _names UNION ALL
SELECT '2', 'two'
) r
ON r._nos = t._no
ORDER BY _no
输出:
row_no _no _name _names
------ ---- --------------- ------
1 1 kratika One
1 kratika kastwar One
1 vikas One
2 2 vikas two
我在 MySQL 这样做
SELECT
CASE WHEN _no = @i THEN '' ELSE @i := _no END
as row_no,
_no,
_name,
r._names
FROM
(
SELECT '1' as _no, 'vikas' as _name UNION ALL
SELECT '1', 'kratika' UNION ALL
SELECT '2', 'vikas' UNION ALL
SELECT '1', 'kratika kastwar'
) t
INNER JOIN
(
SELECT '1' as _nos, 'One' as _names UNION ALL
SELECT '2', 'two'
) r
ON r._nos = t._no
,
(SELECT @i := '') temp
ORDER BY _no
输出:
1 1 vikas One
1 kratika One
1 1 kratika kastwar One
2 2 vikas two
但我希望 MySQL 中的输出像这样
1 1 kratika One
1 kratika kastwar One
1 vikas One
2 2 vikas two
我不想在 MySQL 中使用这样的查询作为desc here MYSQL Order By W/Count
SELECT
CASE WHEN _no = @i THEN '' ELSE @i := _no END
as row_no,
_no,
_name,
_names
FROM
(SELECT
*
FROM
(
SELECT '1' as _no, 'vikas' as _name UNION ALL
SELECT '1', 'kratika' UNION ALL
SELECT '2', 'vikas' UNION ALL
SELECT '1', 'kratika kastwar'
) t
INNER JOIN
(
SELECT '1' as _nos, 'One' as _names UNION ALL
SELECT '2', 'two'
) r
ON r._nos = t._no
,
(SELECT @i := '') temp
ORDER BY _no) t
如何在MySQL中实现相同,查询性能是主要参数
答案 0 :(得分:1)
我认为这里发生的事情是MySQL正在构造结果集,然后经过一个额外的步骤来根据ORDER BY子句对它进行排序。由于'kratika kastwar'
行位于_no
为2
的行之后,因此您会收到意外的输出。
我想,解决方案是将基本的SELECT
(没有特殊的用户变量shenanigans)放在FROM
子句的子查询中,并应用ORDER BY
子句子查询。然后在外部查询中执行用户变量工作。这样排序已经发生了。
编辑:我看到你说你不想这样做。我认为你没有选择,除非你能找到一种方法让MySQL不通过对计算结果执行文件排序步骤来执行ORDER BY
(非常不可能)。
答案 1 :(得分:0)
SELECT
CASE WHEN _no = @i THEN '' ELSE @i := _no END
as row_no,
_no,
_name,
_names
FROM
(SELECT
*
FROM
(
SELECT '1' as _no, 'vikas' as _name UNION ALL
SELECT '1', 'kratika' UNION ALL
SELECT '2', 'vikas' UNION ALL
SELECT '1', 'kratika kastwar'
) t
INNER JOIN
(
SELECT '1' as _nos, 'One' as _names UNION ALL
SELECT '2', 'two'
) r
ON r._nos = t._no
,
(SELECT @i := '')