MySQL:子查询以什么顺序执行?

时间:2015-11-28 19:28:50

标签: mysql subquery

我遇到了一个问题,我的代码正常执行,但只发出“OK”,而不是实际的查询。我将在下面复制它:

CREATE PROCEDURE `Iteration` (Trait VarChar(64))
BEGIN


SET @sql = CONCAT("SELECT Quarter_Year,
IF((SELECT Index_Number FROM TemporaryTable WHERE Stock = 'AAA ' ) = 1, (SELECT ",Trait," FROM Applications.Table WHERE Stock = 'AAA'), NULL) AS AAA,
IF((SELECT Index_Number FROM TemporaryTable WHERE Stock = 'BBB' ) = 2, (SELECT ",Trait," FROM Applications.Table WHERE Stock = 'BBB'), NULL) AS BBB,
IF((SELECT Index_Number FROM TemporaryTable WHERE Stock = 'CCC' ) = 3, (SELECT ",Trait," FROM Applications.Table WHERE Stock = 'CCC'), NULL) AS CCC,
FROM Applications.Table  
GROUP BY Quarter_Year");
PREPARE Statement FROM @sql;
EXECUTE Statement;
DEALLOCATE PREPARE Statement;
END

以上是我创建的程序。它引用了下面执行的TemporaryTable以及对过程的调用。另外,我已经确保过程中的“IF”语句总是评估为TRUE。我必须以如此混乱的方式构造上述内容,因为这是嵌入WHERE语句的唯一方法,可能会影响每一行的调用。

DROP TEMPORARY TABLE IF EXISTS TemporaryTable;
CREATE Table TemporaryTable
(SELECT DISTINCT Index_Number AS Index_Number,
Stock AS Stock
FROM Applications.Table);

CALL Iteration('Trait1');

我现在的操作理论是每行的SELECT部分中的TRUE调用正在正确执行,因为我在某些地方读过在一般查询之前评估它的子查询。

但是,我不确定为什么,如果以上都是正确的,结果只是一个“OK”而不是表格。

非常感谢任何帮助。

更新

我已经开始并采取了一些建议,并尝试执行以下内容,将其从准备好的声明中删除:

SELECT Quarter_Year,
IF((SELECT Index_Number FROM TemporaryTable WHERE Stock = 'AAA ' ) = 1, (SELECT Trait1 FROM Applications.Table WHERE Stock = 'AAA'), NULL) AS AAA,
IF((SELECT Index_Number FROM TemporaryTable WHERE Stock = 'BBB' ) = 2, (SELECT Trait1 FROM Applications.Table  WHERE Stock = 'BBB'), NULL) AS BBB,
IF((SELECT Index_Number FROM TemporaryTable WHERE Stock = 'CCC' ) = 3, (SELECT Trait1 FROM Applications.Table  WHERE Stock = 'CCC'), NULL) AS CCC
    FROM Applications.Table   
GROUP BY Quarter_Year;

不幸的是,它仍然有同样的问题 - 它只会吐出“OK”而不是任何实际结果。 第二次更新

我还尝试了以下代码:

SELECT Quarter_Year,
(SELECT Trait1 FROM Applications.Table WHERE Stock = 'AAA')  AS AAA,
(SELECT Trait1 FROM Applications.Table  WHERE Stock = 'BBB') AS BBB,
(SELECT Trait1 FROM Applications.Table  WHERE Stock = 'CCC') AS CCC
    FROM Applications.Table   
GROUP BY Quarter_Year;

它返回相同的 - “OK”。

我想知道究竟是什么让查询返回OK

第三次更新

Applications.Table就像列一样设置:

  1. Index_Number
  2. Quarter_Year
  3. 一系列特征,包括Trait1,Trait2,Trait3等,作为列头。
  4. 对于Index_Number,它变为1,2,3,4,5等

    Quarter_Year是2008年,2009年,2010年,2011年,2012年,2013年等。

    特征都在0到2之间,所有特征都有小数。

    股票编号只是字母代码。

    所以,例如:

    Index Number  Stock  Quarter_Year    Trait1    Trait2    Trait3
    1              AAA   2009           1.1       0.3        0.5
    2              BBB   2010           1.6       1.2        2.0
    3              CCC   2011           1.3       1.1        0.7
    4              DDD   2012           0.9       0.5        0.4
    5              EEE   2013           0.2       1.9        0.1
    

0 个答案:

没有答案