简体   繁体   English

如何在 MySQL 查询中使用 IF ELSE 语句选择数据

[英]How do select data with IF ELSE statement in a MySQL query

I get data from MySQL with if statement as code below.我使用if语句从 MySQL 获取数据,如下代码所示。 but I get an error: Error Code: 1241. Operand should contain 1 column(s) .但我收到一个错误: Error Code: 1241. Operand should contain 1 column(s)

so can someone can help me?有人可以帮助我吗?

I can not put it into the procedure, because I am using spring + mybatis in the project and i will put this code into them.不能放到程序里,因为我在项目中使用的是spring+mybatis,我会把这段代码放到里面。

SELECT IF((SELECT COUNT(*) FROM table1 WHERE someField = 'A') < 0,
        (SELECT * FROM table2 WHERE someField = 'A'),
        (SELECT * FROM table1 WHERE someField = 'A'))

From the comments: I wanna get data of 1 in 2 tables when table 1 don't have data I will get data from table 2 .来自评论:当表 1 没有数据时,我想获取 2 个表中 1 个的数据,我将从表 2 中获取数据

That sounds like union all and not exists :这听起来像union all not exists

select * from table1 where someField = 'A'
union all
select * from table2 where not exists(select 1 from tabe1 where someField = 'A'

Note that, for this to work, both tables must contain exactly the same number of columns, whith aligned datatypes.请注意,要使其正常工作,两个表必须包含完全相同的列数,以及对齐的数据类型。 You should really be enumerating the columns that you want to show in the resultset in both unioned queries, to avoid any possible ambiguity.您确实应该枚举要在两个unioned查询的结果集中显示的列,以避免任何可能的歧义。 If needed, you can cast columns or add litteral values to any or both of the resultset to align the resultsets (without seeing your actual data structures, I cannot tell how to do).如果需要,您可以cast列或添加文字值到任何或两个结果集以对齐结果集(没有看到您的实际数据结构,我不知道该怎么做)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM