如何使用Mysql SELECT CASE WHEN表达式

时间:2016-07-28 17:29:05

标签: mysql

我正在尝试在mysql DB上使用select case语句。

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>

  <div class="container-fluid">
    <div class="container">
      <h1> Ma gallerie photo </h1>
      <hr>
      <div class="row">
        <div class="col-md-4">
          <img src="http://placehold.it/350x250">
          <div class="hov"></div>
        </div>
        <div class="col-md-4">
          <img src="http://placehold.it/350x250">
          <div class="hov"></div>
        </div>
        <div class="col-md-4">
          <img src="http://placehold.it/350x250">
          <div class="hov"></div>
        </div>
      </div>
      <div class="row">
        <div class="col-md-4">
          <img src="http://placehold.it/350x250">
          <div class="hov"></div>
        </div>
        <div class="col-md-4">
          <img src="http://placehold.it/350x250">
          <div class="hov"></div>
        </div>
        <div class="col-md-4">
          <img src="http://placehold.it/350x250">
          <div class="hov"></div>
        </div>
      </div>
    </div>
  </div>
</body>

错误: ......正确的语法在'AS small,CASE(Amount&gt; 0)

附近使用

我想要我的输出

SELECT 
t.name, t.colour,
CASE WHEN (Amount < 0) AS small,  CASE WHEN (Amount > 0) AS large FROM t

一直没有运气。请帮助。

2 个答案:

答案 0 :(得分:1)

这是:

char

了解SELECT t.name, t.colour, CASE WHEN (t.Amount < 0) THEN t.Amount END AS small, CASE WHEN (t.Amount > 0) THEN t.Amount END AS large FROM t

示例#1:

假设,

CASE WHEN

让我们使用IF n < 0 THEN 'N is negative' else if n == 0 THEN 'N is Zero' else 'N is positive' 表达式在MySQL中转换此if-else if链:

CASE WHEN

<强>输出:

SET @n := -9;
SELECT
CASE WHEN @n <0 THEN 'N is Negative'
     WHEN @n =0 THEN 'N is 0'
     ELSE 'N is positive' END AS output;

示例#2:

现在我们要在MySQL中转换以下三个if语句

    output
N is Negative

<强>输出:

现在输出有三列:

IF n <0 THEN 'N is Negative'
IF n == 0 THEN 'N is Zero'
IF n > 0 THEN 'N is Positive'

SET @n := 5;
SELECT
    CASE WHEN @n <0 THEN 'N is Negative' END AS negativeOutput,
    CASE WHEN @n =0 THEN 'N is 0' END AS zeroOutput,
    CASE WHEN @n > 0 THEN 'N is positive' END AS positiveOutput;

答案 1 :(得分:-2)

您只能为整个表达式设置别名,而不能为表达式的各个组件设置别名:

predict()