[英]MySQL if / else or select if(contiton,'true','false'); - Syntax-problems
當我使用
select if (1=1,'true','false');
然后一切正常,我收到“真實”但如果我嘗試
select if (1=1,(select * from table1), (select * from table2));`
我在 mysql 中收到語法錯誤! 和
if condition then <SQL-Expression1> else <SQL-Expression2> end if;
我有同樣的問題,當 SQL 表達式很復雜時
select * from table1!
如果我使用復雜的 SQL 表達式
select * from table1
或者
insert into table1 (select field1 from table2 where
field1>(select Max(field) from table1));
然后我總是收到一個語法錯誤,當這樣的表達式包含在 if/else-Statement 中時!
我怎樣才能適應它,可以選擇復雜的 sql-Statements?
我的問題是:
我做了2張桌子,比如
create table1 (x1 int4, x2 int4, x3 int4);
create table2 (x int4);
insert into table1 values(1,2,3);
insert into table1 values(4,0,5);
我想將 table1 轉發到 table2
例如:
結果應該像這樣在table2中
1
2
3
4
5
如果我用新行放大表 1
insert into table1 values (6,7,8);
那么 table2 應該更改為
1
2
3
4
5
6
7
8
我試圖以這種方式做到這一點
select if ((select count(*) from table2)=0,
(insert into table2 (select x1 from table1 where x1>0)),
(insert into table2 (select x1 from table1 where
x1>(select Max(x) from table1))));
x2 和 x3 也是如此。 但是出現語法錯誤!
如果我只使用
insert into table2 (select x1 from table1 where x1>(select Max(x) from table1));
如果 table1 不為空,則它有效,否則我必須這樣做
insert into table2 (select x1 from table1 where x1>0);
SELECT 子句中的子查詢可能只返回單個值; 即不超過一個結果,不超過一列。 您不能“欺騙”查詢以返回不同數量的列。
此外,if-then 形式的“if”是為過程 sql 保留的; 用於存儲過程、觸發器等...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.