[英]MySQL if / else or select if(contiton,'true','false'); - Syntax-problems
When I use当我使用
select if (1=1,'true','false');
then everything is ok and I receive 'true' but if I try然后一切正常,我收到“真实”但如果我尝试
select if (1=1,(select * from table1), (select * from table2));`
I receive syntax error in mysql!我在 mysql 中收到语法错误! With
和
if condition then <SQL-Expression1> else <SQL-Expression2> end if;
I have the same problem, when the SQL-Expression is complex like我有同样的问题,当 SQL 表达式很复杂时
select * from table1!
If I use a complex SQL-Expression like如果我使用复杂的 SQL 表达式
select * from table1
or或者
insert into table1 (select field1 from table2 where
field1>(select Max(field) from table1));
then I always receive a syntax error, when such a expression is included in an if/else-Statement!然后我总是收到一个语法错误,当这样的表达式包含在 if/else-Statement 中时!
How can I fit it, that complex sql-Statements can be choosed?我怎样才能适应它,可以选择复杂的 sql-Statements?
My problem is:我的问题是:
I made 2 tables like我做了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);
I wanted to transponse table1 to table2我想将 table1 转发到 table2
For example:例如:
The result should in table2 like this结果应该像这样在table2中
1
2
3
4
5
If I enlarge table 1 with a new line like如果我用新行放大表 1
insert into table1 values (6,7,8);
then table2 should be changed to那么 table2 应该更改为
1
2
3
4
5
6
7
8
I tried to make it in this way我试图以这种方式做到这一点
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))));
The same also with x2 and x3. x2 和 x3 也是如此。 but syntax errors occur!
但是出现语法错误!
If I use only如果我只使用
insert into table2 (select x1 from table1 where x1>(select Max(x) from table1));
then it works if table1 ist not empty otherwise I had to do如果 table1 不为空,则它有效,否则我必须这样做
insert into table2 (select x1 from table1 where x1>0);
Subqueries in the SELECT clause may only return single values; SELECT 子句中的子查询可能只返回单个值; ie not more than one result, and not more than one column.
即不超过一个结果,不超过一列。 You can't "trick" a query into returning a varying number of columns.
您不能“欺骗”查询以返回不同数量的列。
Also, the if-then form of "if" is reserved for procedural sql;此外,if-then 形式的“if”是为过程 sql 保留的; used in stored procedures, triggers, etc...
用于存储过程、触发器等...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.