【发布时间】:2017-06-13 09:26:14
【问题描述】:
假设我有一个如下表:
Table name: trial
ID | Date | Name | Status | Type
1 | 2017-06-01 | ABC | Not Active | Food
2 | 2017-06-02 | DEF | Not Active | Food
3 | 2017-06-03 | GHI | Active | Food
为了从上表中检索最后一个 type = FOOD 的数据,我使用了这个查询
SELECT * FROM `trial` WHERE type = 'FOOD' order by id DESC limit 1
如果我想从 type = FOOD 中检索最新数据,但如果存在 status = active 的数据,则获取此数据。
假设表格条件是这样的。
ID | Date | Name | Status | Type
1 | 2017-06-01 | ABC | Active | Food
2 | 2017-06-02 | DEF | Not Active | Food
3 | 2017-06-03 | GHI | Not Active | Food
我使用这样的查询
SELECT * FROM `trial` WHERE type = 'FOOD' AND status = 'ACTIVE' order by id DESC limit 1
但是如果表格条件随着这个假设而改变呢?
ID | Date | Name | Status | Type
1 | 2017-06-01 | ABC | Not Active | Food
2 | 2017-06-02 | DEF | Not Active | Food
3 | 2017-06-03 | GHI | Not Active | Food
如何从 type = FOOD 检索最新数据,但如果数据 type = food with status is active,则使用 status = active 的数据,但如果没有 active 状态则使用最后一个数据
我应该使用什么 sql 查询?
【问题讨论】:
-
select * from your_table where status='Active';
-
我想要的不仅仅是活动状态而已
-
然后通过 select * from your_table group by status 去分组
-
要从状态处于活动状态的表中选择最新数据,您应该使用
select * from your_table where status='Active' order by ID desc
标签: php mysql codeigniter