1

在 Sql Server 中,我可以执行以下操作:

IF (SELECT COUNT(*) FROM TABLE WHERE COLUMN=VALUE) = 0
SELECT 1,2,3
ELSE SELECT A,B,C FROM TABLE WHERE COLUMN=VALUE

我经常使用它,但现在我必须使用 MySql 并且我无法真正让它工作:)

我想这同样适用于 upsert:

IF (SELECT COUNT(*) FROM TABLE WHERE COLUMN=VALUE) = 0
INSERT INTO TABLE(COLUMN, OTHERCOLUMN) VALUES(VALUE, OTHERVALUE)
ELSE
UPDATE TABLE SET OTHERCOLUMN=OTHERVALUE WHERE COLUMN=VALUE

您如何在 MySql 中执行“if subquery else”?

4

3 回答 3

2

你可以使用这样的东西:

SELECT *
FROM
  (SELECT 1,2,3) s
WHERE
  (SELECT COUNT(*) FROM TABLE WHERE COLUMN=VALUE) = 0
UNION ALL
SELECT
  A,B,C
FROM
  TABLE
WHERE
  COLUMN=VALUE
于 2013-04-30T22:21:47.080 回答
1

假设 a、b 和 c 列没有NULL值,您也可以使用它:

SELECT 
    COALESCE(t.a, 1) AS a,
    COALESCE(t.b, 2) AS b,
    COALESCE(t.c, 3) AS c
FROM 
    (SELECT 1 AS dummy FROM dual) AS d
  LEFT JOIN
    TableX AS t 
      ON t.columnX = Value ;
于 2013-04-30T22:36:34.483 回答
0

像这样...

select * from (
    select a, b, c
    from table t1
    where column = someValue
    union
    select 1, 2, 3) t2 limit 1
于 2013-04-30T22:58:12.420 回答