MYSQL - 条件Where声明

时间:2016-06-27 03:01:23

标签: mysql sql select

需要帮助运行.css语句。基本上我需要在第一个值满足某个条件时使用show all值。

例如,如果我的数据是

.js

我希望能够说出类似的内容:

SELECT

那么我的输出就是

ID |F ID|   DATE |   I     | II   | III   |
===========================================
1  | 11  |  1/26 | peanut  | where| Now   |
-------------------------------------------
2  | 22  |  1/26 | butter  | he   | there |
-------------------------------------------
3  | 11  |  1/27 |  jelly  | at   | he    |
-------------------------------------------
4  | 33  |  1/27 |  time   | huh  | go    |
-------------------------------------------

我唯一能想到的是

if the first F ID = peanut
then show every ID after

4 个答案:

答案 0 :(得分:0)

你的问题很混乱。我希望我理解正确。

  

如果第一个F ID =花生

您需要先获取F_ID并将其存储在变量中:

SELECT @Id = F_ID FROM table WHERE I = 'peanut'

  

然后显示

之后的每个ID

简单地:

SELECT * FROM table WHERE F_ID >= @Id

答案 1 :(得分:0)

您是否尝试过子查询?

SELECT *
FROM `table`
WHERE `F ID`=(
  SELECT `F ID`
  FROM (
    SELECT `F ID`, `I`
    FROM `table`
    ORDER BY `ID`
    LIMIT 1
  ) AS `derived`
  WHERE `I`='peanut'
);

答案 2 :(得分:0)

带连接的经典变体:

SELECT
  t.*
FROM
  table t INNER JOIN (
    SELECT
      F_ID,
      date
    FROM
      table
    WHERE
      I = 'peanut'
  ) t2 ON t2.F_ID = t.F_ID AND t2.date >= t.date

答案 3 :(得分:0)

您可以使用SUB QUERY获取它 例 SELECT * FROM F_VAL;

+------+------+------+--------+-------+-------+
| ID   | F_ID | DATE | I      | II    | III   |
+------+------+------+--------+-------+-------+
|    1 |   11 | 1/26 | peanut | where | Now   |
|    2 |   22 | 1/26 | butter | he    | there |
|    3 |   11 | 1/27 |  jelly | at    | he    |
|    4 |   33 | 1/27 |  time  | huh   | go    |
|    1 |   11 | 1/25 | cake   | where | Now   |
+------+------+------+--------+-------+-------+

5行(0.01秒)

如果您想要以这种状态获得所有记录

 SELECT * FROM F_VAL WHERE F_ID = (SELECT F_ID FROM F_VAL WHERE `I`='peanut');
+------+------+------+--------+-------+-------+
| ID   | F_ID | DATE | I      | II    | III   |
+------+------+------+--------+-------+-------+
|    1 |   11 | 1/26 | peanut | where | Now   |
|    3 |   11 | 1/27 |  jelly | at    | he    |
|    1 |   11 | 1/25 | cake   | where | Now   |
+------+------+------+--------+-------+-------+
3 rows in set (0.00 sec))

如果您想在第一次创建日期之后创建所有记录

mysql> SELECT F.* FROM F_VAL F INNER JOIN  (SELECT F_ID,DATE FROM F_VAL WHERE `I`='peanut') X ON X.F_ID=F.F_ID AND F.DATE>=X.DATE ;
+------+------+------+--------+-------+-------+
| ID   | F_ID | DATE | I      | II    | III   |
+------+------+------+--------+-------+-------+
|    1 |   11 | 1/26 | peanut | where | Now   |
|    3 |   11 | 1/27 |  jelly | at    | he    |
+------+------+------+--------+-------+-------+
2 rows in set (0.00 sec)