简体   繁体   English

根据 MySQL 中的值选择字段

[英]Select field based on value in MySQL

There is mysql table foo :有 mysql 表foo

a | b | c
----------
1 | 2 | 0
2 | 3 | 1
3 | 4 | 0

and a query和一个查询

SELECT a-b as subA, b-a as subB FROM foo;

subA | subB
-----------
 -1  |   1
 -1  |   1
 -1  |   1

How can I select ab as sum if c = 0 and ba as sum if c = 1, so that I have this result:如果 c = 0,我如何选择ab as sum ba as sum如果 c = 1,我如何选择ba as sum ,以便得到以下结果:

sum
---
-1
 1
-1
SELECT (a-b)*(1-2*c) AS `sum`
FROM foo

You can use a case expression:您可以使用case表达式:

select f.*,
    case c 
        when 0 then a - b 
        when 1 then b - a
    end as res
from foo f

If c is always 0 or 1 , we can get a little fancy with sign() :如果c总是01 ,我们可以对sign()有点幻想:

select f.*, sign(c - 0.5) * (b - a) as res 
from foo f

This is pretty simple (look in SQLize.online ):这非常简单(查看SQLize.online ):

SELECT 
    a-b as subA, 
    b-a as subB,
    CASE 
        WHEN c = 0 THEN a-b
        WHEN c = 1 THEN b-a
    END as sum
FROM foo;

Result:结果:

+======+======+=====+
| subA | subB | sum |
+======+======+=====+
| -1   | 1    | -1  |
+------+------+-----+
| -1   | 1    | 1   |
+------+------+-----+
| -1   | 1    | -1  |
+------+------+-----+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM