1

我已经定义:
表 X

ID    AGE    HEIGHT   REGISTERED
1     23     1.83     1
2     24     1.81     0
3     24     1.72     0
4     22     1.91     1
5     32     1.76     0

我想执行一个查询以返回有效值,但*ONLY*对于注册的 ID。那些不是,将得到0作为回报。像这样:

结果

ID    AGE    HEIGHT   REGISTERED
1     23     1.83     1
2     0      0        0
3     0      0        0
4     22     1.91     1
5     0      0        0

定义该查询的方式是什么?

4

3 回答 3

4

您可以使用 MySQL 特定的IF表达式:

SELECT 
    ID,
    IF(REGISTERED, AGE, 0) AS AGE,
    IF(REGISTERED, HEIGHT, 0) AS HEIGHT,
    REGISTERED
FROM tablex

在线查看它:sqlfiddle

您还可以使用标准 SQLCASE表达式:

SELECT 
    ID,
    CASE WHEN REGISTERED = 1 THEN AGE ELSE 0 END AS AGE,
    CASE WHEN REGISTERED = 1 THEN HEIGHT ELSE 0 END AS HEIGHT,
    REGISTERED
FROM tablex

作为对您的评论的回应,如果您有很多列,这里可能会稍微容易一些:

SELECT id, AGE, HEIGHT, REGISTERED
FROM tablex
WHERE REGISTERED

UNION ALL

SELECT id, 0, 0, 0
FROM tablex
WHERE NOT REGISTERED

ORDER BY ID

在线查看它:sqlfiddle

请注意,此查询中的列列表可以缩短为 justSELECT *并且查询仍然有效。但是SELECT *由于网站其他地方已经介绍过的各种原因,不建议在生产代码中使用。

于 2012-07-18T22:35:11.337 回答
1

您可以在 SQL 中使用 IF

SELECT
  ID,
  IF(REGISTERED = 1, AGE, 0) AS AGE,
  IF(REGISTERED = 1, HEIGHT, 0) AS HEIGHT,
  REGISTERED
FROM TableX
于 2012-07-18T22:36:05.843 回答
0

你也可以这样做

SELECT ID, Age, Height, Registered FROM (SELECT ID, Age, Height, Registered FROM TableX WHERE Registered = 1 UNION ALL SELECT ID, 0 AS Age, 0 AS Height, Registered FROM TableX WHERE Registered = 0) ORDER BY ID

于 2012-07-18T22:56:07.910 回答