如何选择有条件的数据

时间:2014-01-17 07:01:07

标签: php mysql sql select

我试图检索某个日期范围内的所有数据行,只有1个条件只检索'balance'类型的第一行,我想我的问题应该用数据样本更好地解释。

这是我的表声明

| 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

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

3 个答案:

答案 0 :(得分:2)

你试过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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

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