如何仅在某些情况下应用UNION(MySQL)

时间:2019-10-09 22:11:55

标签: mysql

我有以下内容-简化的查询:

@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
    private static String DEFAULT_VALIDATION_ERROR_CODE = "KC-0020";

    @ExceptionHandler(MiddlewareException.class)
    protected ResponseEntity<ResponseBody> handleKidsClubException(MiddlewareException ex) {
        return buildErrorResponse(HttpStatus.valueOf(ex.getHttpStatus()), ex.toError());
    }

    @ExceptionHandler(ServiceUnavailableException.class)
    protected ResponseEntity<ResponseBody> handleServiceUnavailable(ServiceUnavailableException ex) {
        return buildErrorResponse(INTERNAL_SERVER_ERROR, ex);
    }

    @ExceptionHandler(NoSuchElementException.class)
    protected ResponseEntity<ResponseBody> handleNoFoundElement(NoSuchElementException ex) {
        return buildErrorResponse(NOT_FOUND, ex);
    }

    @ExceptionHandler(CouchbaseQueryExecutionException.class)
    protected ResponseEntity<ResponseBody> handleCouchbaseQueryException(ConstraintViolationException ex) {
        return buildErrorResponse(BAD_REQUEST, ex);
    }
}

但是,我只希望在查询的第一部分返回至少一个结果的情况下附加UNION部分,例如:

table_x有一个条目(id = 1):

SELECT id
FROM table_x
UNION ALL 
SELECT 0 AS id

table_x空:

table_x: 1
Current and desired result: 1, 0

在查询中有什么方法可以做到这一点?预先非常感谢。

2 个答案:

答案 0 :(得分:0)

只要您的表存在。你可以做这样的事情。

SELECT
IF ( a is NULL, NULL, CONCAT(a,",",b))
FROM(
SELECT
  (SELECT * From myTable WHERE id = 2) a
  ,(SELECT 0) b
  ) C

结果为空

id = 1的结果 会是

IF ( a is NULL, NULL, CONCAT(a,",",b))
1,0

答案 1 :(得分:0)

非常感谢您的回答。我通过以下方法解决了这个问题:

public showAccepterPart() {
    if (this.numContact !== '') {
      const url = 'server_address/app/interv-app/API-SERVER/AccepterPart.php';
      const dataPost = JSON.stringify({
        numContact : this.numContact,
      });
      this.http.post(url, dataPost).map(res => res.json()).subscribe(data => {
        this.AccepterPart = data;
      });
      this.nativeStorage.setItem(this.key7, JSON.stringify(this.AccepterPart));
      console.log('numContact : ' + this.numContact);
    } else {
      console.log('Pas de numéro');
    }
  }