sql SELECT 如果存在
sql SELECT in IF EXISTS
我正在尝试 运行 这个 :
IF EXISTS (SELECT id_commande FROM historique WHERE id_commande = 57 AND device = 70635601)
BEGIN
SELECT id_commande FROM historique WHERE id_commande = 57 AND device = 70635601
END
ELSE
BEGIN
SELECT (MAX(id_commande)+1) FROM historique
END
我希望你能明白我想做什么。我的问题是它总是给我返回 Erreur dans la requête (1064): Syntax error near 'BEGIN SELECT 1 END ELSE BEGIN SELECT 2 END' at line 2
.
谢谢你帮助我!
我认为您正在尝试使用 CASE
语句:
SELECT CASE WHEN EXISTS (SELECT id_commande FROM historique WHERE id_commande = 57 AND device = 70635601) THEN 1 ELSE 2 END;
您可以在没有 EXISTS
的情况下使用 COALESCE()
:
SELECT
COALESCE(
(SELECT id_commande FROM historique WHERE id_commande = 57 AND device = 70635601),
(SELECT MAX(id_commande) + 1 FROM historique)
)
我假设第一个查询 return 只有 1 行。
您可以 LEFT JOIN 到带有值的子查询。
然后合并值或最大值。
例如:
create table historique
(
id int primary key auto_increment,
device int,
id_commande int
);
insert into historique
(device, id_commande) values
(70635601, 57),
(70635601, 63);
查询:
SELECT
coalesce(
max(case
when val.id_commande = hist.id_commande
then hist.id_commande
end),
max(hist.id_commande)+1,
1
) as id_commande
FROM (
select
70635601 as device,
57 as id_commande
) val
LEFT JOIN historique hist
ON hist.device = val.device
GROUP BY val.device
| id_commande |
| ----------: |
| 57 |
db<>fiddle here
我正在尝试 运行 这个 :
IF EXISTS (SELECT id_commande FROM historique WHERE id_commande = 57 AND device = 70635601)
BEGIN
SELECT id_commande FROM historique WHERE id_commande = 57 AND device = 70635601
END
ELSE
BEGIN
SELECT (MAX(id_commande)+1) FROM historique
END
我希望你能明白我想做什么。我的问题是它总是给我返回 Erreur dans la requête (1064): Syntax error near 'BEGIN SELECT 1 END ELSE BEGIN SELECT 2 END' at line 2
.
谢谢你帮助我!
我认为您正在尝试使用 CASE
语句:
SELECT CASE WHEN EXISTS (SELECT id_commande FROM historique WHERE id_commande = 57 AND device = 70635601) THEN 1 ELSE 2 END;
您可以在没有 EXISTS
的情况下使用 COALESCE()
:
SELECT
COALESCE(
(SELECT id_commande FROM historique WHERE id_commande = 57 AND device = 70635601),
(SELECT MAX(id_commande) + 1 FROM historique)
)
我假设第一个查询 return 只有 1 行。
您可以 LEFT JOIN 到带有值的子查询。
然后合并值或最大值。
例如:
create table historique ( id int primary key auto_increment, device int, id_commande int ); insert into historique (device, id_commande) values (70635601, 57), (70635601, 63);
查询:
SELECT coalesce( max(case when val.id_commande = hist.id_commande then hist.id_commande end), max(hist.id_commande)+1, 1 ) as id_commande FROM ( select 70635601 as device, 57 as id_commande ) val LEFT JOIN historique hist ON hist.device = val.device GROUP BY val.device
| id_commande | | ----------: | | 57 |
db<>fiddle here