【问题标题】:Prepending a row in the result of a MySQL query?在 MySQL 查询的结果中添加一行?
【发布时间】:2017-03-07 08:18:34
【问题描述】:

阅读this answer 到关于如何将行附加到 MySQL 结果的 SO 问题,我们可以执行以下操作将值 Jason 附加到客户的名称:

Select NAME
From Customers
UNION ALL
Select 'Jason'

所以我们最终得到:

NAME
Actual Customer 1
Actual Customer 2
Jason

但是我们如何将 Jason 添加到结果的开头,所以我们有:

NAME
Jason
Actual Customer 1
Actual Customer 2

(希望不使用 Order By 来执行此操作)

【问题讨论】:

  • Select 'Jason' as Name UNION ALL Select Name From Customers
  • “想在不使用 Order By 的情况下执行此操作” - 为什么?
  • @onedaywhen 因为我实际上是使用日期而不是名称来执行此操作,所以在这种情况下排序效果不佳,并且我得到了不需要的结果。
  • 那么在这种情况下,在您的问题中使用日期可能是明智的。 不会吗? 如果我将 2 个苹果加到 3 个苹果,我会得到什么? 现在肯定不是 ORANGES 了吧?
  • @RiggsFolly 可能有,但在我看来它使它变得更加复杂,而且除了要说我想将字符串值附加到日期列表之外。

标签: mysql


【解决方案1】:

你试过了吗

Select 'Jason' As `Name`
UNION ALL
Select Name
From Customers

如果您想订购第二个查询,请使用类似

Select 'Jason' As `Name`
UNION ALL
(Select `myDate`
From Customers
Order By `myDate`
)

【讨论】:

  • 感谢您加倍努力,因为它帮助我更多地了解 MySQL :-)
  • 您的第二个查询可以简化为Select 'Jason' As Name UNION ALL (Select Name From Customers order by some_column)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多