简体   繁体   English

在mysql中设置结果的情况

[英]Case with result set in mysql

I want's to test following query in mysql 我想在mysql中测试以下查询

SELECT result.* FROM 
(CASE WHEN (2 = 2) 
THEN
(SELECT * FROM mytable WHERE myID =2814 )
END) result ;

but it is sending syntax error. 但它正在发送语法错误。 Any idea what's wrong with it ? 知道这有什么问题吗?

you can do it in a round about way like so 你可以像这样绕一圈

SET @query := NULL;

SELECT @query := t.qry 
FROM 
(   SELECT 
        CASE WHEN 2 = 2
             THEN "SELECT * FROM mytable WHERE myID =2814"
             WHEN another_condition
             THEN "another_select"
        END as qry
) t ;

PREPARE query1 FROM @query;
EXECUTE query1;

This is too long for a comment. 这个评论太长了。

Obviously, your query is equivalent to: 显然,您的查询等效于:

SELECT *
FROM mytable
WHERE myID = 2814;

This makes it a bit hard to figure out what you are asking. 这使您很难弄清您的要求。

Fundamentally, though case is an expression, and the from clause does not accept expressions. 从根本上讲, case是一个表达式,而from子句不接受表达式。 It accepts table names, view names, subqueries, and the like. 它接受表名,视图名,子查询等。 Second, the case statement has a few other problems. 其次, case陈述还有其他一些问题。

  • It returns a scalar scalar value. 它返回一个标量标量值。 The subquery could return more than one row. 子查询可能返回多个行。
  • Returning more than one column is not allowed 不允许返回多列
  • All the clauses need to return the same thing 所有子句都需要返回相同的内容

If you wanted to select from multiple tables -- and all of them have the same structure -- you can use a union all construct: 如果要从多个表中选择-并且它们都具有相同的结构-可以使用并union all构造:

select t.*
from table2 t
where . . .
union all
select t.*
from table2 t
where . . .

I would prefer to use a different query each time (which at least will allow mysql some chance of using indexes properly). 我宁愿每次都使用不同的查询(至少这将使mysql有机会正确使用索引)。

However assuming there are several sub queries that you want as a source for data depending on the check then maybe something like this:- 但是,假设根据检查,有几个子查询要作为数据源,则可能是这样的:

SELECT result.* 
FROM 
(
    SELECT * FROM mytable WHERE 2 = 2 AND myID = 2814  
    UNION
    SELECT * FROM mytable2 WHERE 1 = 2 AND myID = 2814  
    UNION
    SELECT * FROM mytable3 WHERE 3 = 2 AND myID = 2814  
) result ;

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

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