【问题标题】:Ordering by a field not in the select statement in SQL按不在 SQL 中的 select 语句中的字段排序
【发布时间】:2014-11-05 12:51:33
【问题描述】:

我需要创建一个只提取 customer_no 列的查询(因为软件限制就是这样,我无法在外部对其进行编码)。但我需要能够按 create_dt (反向)列对数据进行排序。代码/SQL 限制了我使用以下内容,因为为了按某些内容进行排序,数据必须出现在 select 语句中。

我不能让它出现在那里——有什么办法解决这个问题吗?

 Select Distinct top 3500 a.customer_no 
  From T_CUSTOMER a  WITH (NOLOCK)
  JOIN (Select a1.customer_no From VXS_CUST_TKW a1 WITH (NOLOCK) Where a1.tkw in (141)) as e ON      e.customer_no = a.customer_no
  Where 1 = 1
 order by a.create_dt desc

【问题讨论】:

  • 我从来没有遇到过 MySQL 的问题。另一方面,MySQL 没有TOP 3500,您必须在查询末尾使用LIMIT 3500。你确定你使用的是 MySQL 吗?
  • 它的事务 SQL。我相信。我正在通过软件工作 - 在前端。也就是说,前 3500 名的作品没有问题 - 但排序不起作用。
  • You're WHERE 子句没有用,为什么会有呢?
  • 您是否知道在每次查询中抛出 NOLOCK 的后果?您可以并且将会丢失和/或重复行。 jasonstrate.com/2012/06/the-side-effect-of-nolock
  • @JohnRuddell 系统自己创建语法 - 但是当我们需要过滤/修改它时 - 这通常是 - 我们在代码模式下打开它并进行更改。但我们尽量不做太多更改,因为我们并不总是有能力对其进行测试。

标签: sql tsql join sql-order-by


【解决方案1】:

当然可以。您的查询看起来像 SQL Server,这可能会执行您想要的操作:

  Select top 3500 a.customer_no 
  From T_CUSTOMER a  WITH (NOLOCK) JOIN
       (Select a1.customer_no
        From VXS_CUST_TKW a1 WITH (NOLOCK)
        Where a1.tkw in (141)
       ) e
       ON e.customer_no = a.customer_no
  Where 1 = 1
  group by a.customer_no
  order by max(a.create_dt) desc;

MySQL 中的等效查询如下所示:

  Select a.customer_no 
  From T_CUSTOMER a JOIN
       (Select a1.customer_no
        From VXS_CUST_TKW a1 
        Where a1.tkw in (141)
       ) e
       ON e.customer_no = a.customer_no
  Where 1 = 1
  order by a.create_dt desc
  limit 3500;

我删除了distinct,因为它可能没有必要。如果是,请重新添加。

【讨论】:

  • 我使用您的查询 - 第一个查询,它似乎工作,但只要我在单词 select 之后添加 Distinct,我就会收到以下错误:Order By items must appear in the select list if select distinct被指定(-1),我似乎无法摆脱它。
  • @YelizavetaYR 。 . .最简单的解决方案是使用group by 而不是distinct。我修改了第一个查询。
【解决方案2】:

这看起来不像mysql。

无论如何...你可以尝试一个有序的子选择 IE

From (select * from T_CUSTOMER order by create_dt) a WITH (NOLOCK)

我希望这会有所帮助。

【讨论】:

    【解决方案3】:

    使用包含您排序依据的列的子查询。那么主查询就可以只返回你关心的列了:

    SELECT customer_no
    FROM (
        Select top 3500 a.customer_no, a.create_dt
          From T_CUSTOMER a  WITH (NOLOCK) JOIN
               (Select a1.customer_no
                From VXS_CUST_TKW a1 WITH (NOLOCK)
                Where a1.tkw in (141)
               ) e
               ON e.customer_no = a.customer_no
          Where 1 = 1
          order by a.create_dt desc
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-25
      • 2021-05-14
      • 2014-12-05
      相关资源
      最近更新 更多