SQL Table:

SQL表:

-----------------------------------------
| ID  |   COLOR   |         DATE        |
|-----|-----------|---------------------|
|  1  | ORANGE    | 2011-11-03 01:14:00 |
|  2  | YELLOW    | 2011-11-03 01:13:00 |
|  3  | GREEN     | 2011-11-03 01:16:00 |
|  4  | BLUE      | 2011-11-03 01:16:00 |
|  5  | PINK      | 2011-11-03 01:12:00 |
-----------------------------------------

The following query gives me the results ordered by date:

以下查询给出了按日期排序的结果:

SELECT *
FROM `table`
ORDER BY `date` DESC
LIMIT 0, 4

-----------------------------------------
| RESULT:                               |
|---------------------------------------|
|  3  | GREEN     | 2011-11-03 01:16:00 |
|  4  | BLUE      | 2011-11-03 01:16:00 |
|  1  | ORANGE    | 2011-11-03 01:14:00 |
|  2  | YELLOW    | 2011-11-03 01:13:00 |
-----------------------------------------

But what if I wanted to order it by date and also start from a specific 'color'?

但是如果我想按日期订购并从特定的“颜色”开始呢?

SELECT *
FROM `table`
ORDER BY `date` DESC
LIMIT 0, 4
START WHERE `color`='blue'

-----------------------------------------
| RESULT I WANT:                        |
|---------------------------------------|
|  4  | BLUE      | 2011-11-03 01:16:00 |
|  1  | ORANGE    | 2011-11-03 01:14:00 |
|  2  | YELLOW    | 2011-11-03 01:13:00 |
|  5  | PINK      | 2011-11-03 01:12:00 |
-----------------------------------------

^What is the correct syntax to get this result?

^获得此结果的正确语法是什么?

1 个解决方案

#1


3

SELECT 
  y.*
FROM
  YourTable y
WHERE
  y.date <= (SELECT yb.date FROM YourTable yb WHERE yb.color = 'BLUE')
ORDER BY
  y.date DESC
LIMIT 4 OFFSET 0

Updated:

更新:

SELECT 
  y.*
FROM
  YourTable y
WHERE
  /* The colors 'before' blue */
  y.date < (SELECT yb.date FROM YourTable yb WHERE yb.color = 'BLUE') or
  /* And blue itself */
  y.color = 'BLUE'
ORDER BY
  y.date DESC
LIMIT 4 OFFSET 0

Second update to meet newly discovered criteria.

第二次更新以满足新发现的标准。

SELECT 
  y.*
FROM
  YourTable y,
  (SELECT yb.id, yb.date FROM yb WHERE color = 'GREEN') ys
WHERE
  /* The colors 'before' green */
  y.date < ys.date or
  /* The colors on the same date as green, but with greater 
     or equal id to green. This includes green itself.
     Note the parentheses here. */
  (y.date = ys.date and y.id >= ys.id)
ORDER BY
  y.date DESC
LIMIT 4 OFFSET 0

更多相关文章

  1. 无法弄清楚mySQL语法错误的来源
  2. 从Access表将数据导入Excel,从子句中出现语法错误
  3. 在多个查询和子查询中更正连接语法
  4. 背景图像颜色检测与Android油漆。
  5. 根据给出的语料库,训练n-gram模型。根据训练出的模型,判断测试集中
  6. Android Toolbar返回按钮颜色修改
  7. Android 自定义控件 改变图片颜色来实现类似selector点击更改颜
  8. Android开发笔记——改变字体颜色的三种方法
  9. 更改Edittext光标的颜色与粗细

随机推荐

  1. 浅析Android中的消息机制
  2. android实现软件指导页
  3. Android判断真机和模拟器
  4. Android 软键盘弹出时,把整个界面往上挤
  5. android SQLiteDatabase 错误 database d
  6. android 自动更新apk版本
  7. android刮刮奖效果
  8. Android Layout Tricks #2: Reusing layo
  9. Android 程序启动界面Demo
  10. Android实现音乐的播放与停止(Service的初