在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'吗?
答案 0 :(得分: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
答案 1 :(得分: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 ;
答案 2 :(得分:0)
喜欢这个......
select * from (
select a, b, c
from table t1
where column = someValue
union
select 1, 2, 3) t2 limit 1