MySQL 查询和子查询

Posted

技术标签:

【中文标题】MySQL 查询和子查询【英文标题】:MySQL query and subquery 【发布时间】:2015-09-11 19:40:41 【问题描述】:

我有一个这样的查询:

SELECT SUM(price) AS GINTO,
(
   (SELECT COUNT(price)*9.99 FROM sms_logs WHERE price = '200000')+
   (SELECT COUNT(price)*3.99 FROM sms_logs WHERE price = '60000')+
   (SELECT COUNT(price)*1.99 FROM sms_logs WHERE price = '24000')+
   (SELECT COUNT(price)*0.99 FROM sms_logs WHERE price = '11000')
) AS USD,
DATE_FORMAT(DATE,'%Y-%m-%d') AS DATE FROM sms_logs 
WHERE DATE >='2015-03-20' AND DATE <= '2015-04-30'
GROUP BY DATE_FORMAT(DATE,'%Y-%m-%d')

我想将数据显示为:

 GINTO  ||   USD  ||   DATE
2222000 ||   200  || 2015-03-23
3366000 ||   300  || 2015-03-24
11000   ||   10   || 2015-03-25

但该查询的结果:

 GINTO  ||   USD ||   DATE
2222000 || 284.65|| 2015-03-23
3366000 || 284.65|| 2015-03-24
11000   || 284.65|| 2015-03-25

使用 USD 列,它显示所有记录的摘要。为什么?

【问题讨论】:

您需要提供一些样本数据和预期结果集的逻辑,最好是sqlfiddle.com中的样本数据 【参考方案1】:

试试这个

SELECT SUM(price) AS GINTO,
SUM(case when price = '200000' then 1 else 0 end*9.99)+
SUM(case when price = '60000' then 1 else 0 end*3.99)+
SUM(case when price = '24000' then 1 else 0 end*1.99)+
SUM(case when price = '11000' then 1 else 0 end*0.99) AS USD,
DATE_FORMAT(DATE,'%Y-%m-%d') AS DATE FROM sms_logs 
WHERE DATE >='2015-03-20' AND DATE <= '2015-04-30'
GROUP BY DATE_FORMAT(DATE,'%Y-%m-%d')

【讨论】:

【参考方案2】:

您的count 调用在单独的查询中运行,没有group by 子句,因此它们应用于整个表,而不管“主”查询的分组。解决这个问题的一种方法是去掉子查询并将它们带入“主”查询:

SELECT   SUM(price) AS GINTO,
         SUM(CASE price WHEN '200000' THEN 9.99
                        WHEN '60000'  THEN 3.99
                        WHEN '24000'  THEN 1.99
                        WHEN '11000'  THEN 0.99
              END) AS usd,
         DATE_FORMAT(date, '%Y-%m-%d') AS date 
FROM     sms_logs 
WHERE    date >='2015-03-20' AND date <= '2015-04-30'
GROUP BY DATE_FORMAT(date,'%Y-%m-%d')

【讨论】:

【参考方案3】:

你可以试试下面的查询-

SELECT SUM(price) AS GINTO, 
      (COUNT(IF(price='200000',price,NULL))*9.99 +  
       COUNT(IF(price='60000',price,NULL))*3.99 + 
       COUNT(IF(price='24000',price,NULL))*1.99 + 
       COUNT(IF(price='11000',price,NULL))*0.99) AS USD, 
DATE_FORMAT(date_col,'%Y-%m-%d') AS 'Date' 
FROM sms_logs 
WHERE date_col >='2015-03-20' AND date_col <= '2015-04-30'
GROUP BY DATE(date_col)

【讨论】:

以上是关于MySQL 查询和子查询的主要内容,如果未能解决你的问题,请参考以下文章

带有连接和子查询的 mysql 查询优化

MySQL多表查询和子查询

mysql中,如何向测试人员介绍连接查询和子查询的优劣势?

MySql 技术内幕 (查询处理和子查询)

MySql 技术内幕 (查询处理和子查询)

MySQL查询和子查询不熟练