【问题标题】:How to select data with condition如何选择有条件的数据
【发布时间】:2014-01-17 07:01:07
【问题描述】:

我正在尝试检索某个日期范围内的所有数据行,其中只有一个条件,即仅检索“余额”类型的第一行,我认为我的问题应该用数据样本更好地解释。

这是我的表格声明

| date | type     | credit | debit | balance |
|   a  | balance  |        |       |  100.00 |
|   a  | credit   | 50.00  |       |         |
|   a  | credit   | 50.00  |       |         |
|   a  | debit    |        | 50.00 |         |
|   b  | balance  |        |       |  50.00  |
|   b  | credit   | 50.00  |       |         |
|   b  | credit   | 50.00  |       |         |
|   b  | credit   | 50.00  |       |         |
|   b  | balance  |        |       | -100.00 |
|   c  | debit    |        | 250.00|         |

这就是我想要做的(预期结果)

我需要执行一个查询,返回从日期 a 到 c 的所有行,但只返回类型为 balance 的第一行

| date | type     | credit | debit | balance |
|   a  | balance  |        |       |  100.00 |
|   a  | credit   | 50.00  |       |         |
|   a  | credit   | 50.00  |       |         |
|   a  | debit    |        | 50.00 |         |
|   b  | credit   | 50.00  |       |         |
|   b  | credit   | 50.00  |       |         |
|   b  | credit   | 50.00  |       |         |
|   c  | debit    |        | 250.00|         |

我在这里知道的是我可以通过执行 2 个不同的查询来实现

SELECT * FROM statement WHERE date >= a and date <= c and type = 'balance' ORDER BY date ASC LIMIT 1
SELECT * FROM statement WHERE date >= a and date <= c and type != 'balance' ORDER BY date ASC

这是我的问题,出于某种原因,我需要使用 1 个单一查询来完成此操作,我如何通过一个查询来实现此结果。

【问题讨论】:

  • 您的第一个查询的限制为 1,因此您只能获得一行
  • 联盟以外的?我试过了,但它搞砸了我的 php 类......我正在尝试挖掘更简单的查询

标签: php mysql sql select


【解决方案1】:

您尝试过 UNION 吗?

SELECT * FROM statement WHERE date >= a and date <= c and type = 'balance' ORDER BY date ASC LIMIT 1
UNION
SELECT * FROM statement WHERE date >= a and date <= c and type != 'balance' ORDER BY date ASC

【讨论】:

    【解决方案2】:

    Uniondistinct 一起使用

    SELECT * FROM statement WHERE date >= a and date <= c and type = 'balance' ORDER BY date ASC LIMIT 1
    UNION DISTINCT
    SELECT * FROM statement WHERE date >= a and date <= c and type != 'balance' ORDER BY date ASC
    

    【讨论】:

      【解决方案3】:

      我认为您不需要同时提供type = 'balance'type != 'balance' 条件。这没有任何意义。以下查询将获取相同的记录。

      SELECT * 
      FROM statement 
      WHERE date >= a and date <= c  ORDER BY type,date ASC 
      

      【讨论】:

      • 我认为 CASE 可能会有所帮助,请再次阅读我的问题,我想在第一行输入 balance
      • @LeonArmstrong 那么为什么不使用 order by 类型而不是日期呢?
      • 检查预期结果,我想要所有行,但在第一个被选择后忽略类型为 balance 的行
      猜你喜欢
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-12
      相关资源
      最近更新 更多