0

我在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 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 中实现相同的功能,查询性能是主要参数

4

2 回答 2

1

我认为这里发生的事情是 MySQL 正在构建结果集,然后通过一个额外的步骤根据 ORDER BY 子句对其进行排序。由于该'kratika kastwar'行位于 where _nois行之后2,因此您会得到意外的输出。

我想,解决方案是将基本SELECT(没有特殊的用户变量恶作剧)放在子句的子查询中FROM,将ORDER BY子句应用于子查询。然后在外部查询中执行用户变量工作。这样订购就已经发生了。

编辑:我看到你说你不想这样做。我认为您别无选择,除非您可以ORDER BY通过对计算结果执行文件排序步骤(非常不可能)找到一种方法让 MySQL 不这样做。

于 2013-01-30T09:16:11.857 回答
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 := '') 
于 2013-01-30T09:06:53.147 回答