如何处理此错误1242(21000):子查询返回超过1行

时间:2014-01-15 15:41:42

标签: mysql sql

大家好,我遇到SQL查询问题,谷歌搜索了很多,但找不到任何解决方案。这是我的代码:

 SELECT (SELECT ltp 
         FROM eod_stock  
         WHERE company_id IN (1,2) 
             AND entry_date = '2013-09-24') AS b,
        (SELECT ltp 
         FROM eod_stock  
         WHERE company_id IN (1,2) 
             AND entry_date = '2013-09-25') AS e,
        CAST(((SELECT ltp 
               FROM eod_stock  
               WHERE company_id IN(1,2) 
                   AND entry_date = '2013-09-25') -
              (SELECT ltp 
               FROM eod_stock  
               WHERE company_id IN (1,2) 
                   AND entry_date = '2013-09-24')) /
              (SELECT ltp  
               FROM eod_stock  
               WHERE company_id IN (1,2) 
                   AND entry_date = '2013-09-25')*100 
             AS DECIMAL(10,2)) AS c;

它给了我错误

ERROR 1242 (21000): Subquery returns more than 1 row

我理解错误导致我的查询应该返回超过1行,因为我通过2公司,但我需要所有公司ltp,我在我的查询中提到。结果需要如下:

+--------+--------+--------+
| b      | e      | c      |
+--------+--------+--------+
| 460.00 | 338.00 | -36.09 |
+--------+--------+--------+
| 320.00 | 488.00 |  34.42 |
+--------+--------+--------+

任何人都可以建议我如何从我的查询中获得这样的多个结果?因为我必须在查询中传递超过1个公司ID。

表格结构:

+-----------------+------------------+------+-----+---------+-------+
| Field           | Type             | Null | Key | Default | Extra |
+-----------------+------------------+------+-----+---------+-------+
| company_id      | varchar(30)      | NO   | PRI | NULL    |       |
| entry_date      | date             | NO   | PRI | NULL    |       |
| entry_timestamp | int(10) unsigned | NO   |     | NULL    |       |
| open            | decimal(16,2)    | NO   |     | NULL    |       |
| high            | decimal(16,2)    | NO   |     | NULL    |       |
| low             | decimal(16,2)    | NO   |     | NULL    |       |
| ltp             | decimal(16,2)    | NO   |     | NULL    |       |
| ycp             | decimal(16,2)    | NO   |     | NULL    |       |
| cse_price       | decimal(9,2)     | NO   |     | NULL    |       |
| cse_volume      | decimal(18,2)    | NO   |     | NULL    |       |
| total_trade     | int(30)          | NO   |     | NULL    |       |
| total_volume    | int(30)          | NO   |     | NULL    |       |
| total_value     | decimal(18,4)    | NO   |     | NULL    |       |
+-----------------+------------------+------+-----+---------+-------+

1 个答案:

答案 0 :(得分:5)

从子查询中选择时,您只能获得一行。

您可以自己加入表格并选择您感兴趣的两个日期的行。这样的事情应该有效。

SELECT a.ltp, b.ltp, CAST(((b.ltp - a.ltp) / b.ltp * 100) AS DECIMAL(10, 2))
FROM eod_stock a
JOIN eod_stock b ON a.company_id = b.company_id
WHERE a.entry_date = "2013-09-24"
AND b.entry_date = "2013-09-25"
AND a.company_id IN (1, 2)