mysql未知列

时间:2010-10-13 00:47:24

标签: mysql

我正在使用此查询

SELECT COUNT(DISTINCT to_number) AS errors FROM sent_txts
WHERE msg_link_id = 0 AND 
msg_sent_datetime BETWEEN '2010-08-09 07:00:00' AND '2010-09-07 11:59:59'
HAVING to_number IN(SELECT mobile FROM action_6_members WHERE mobile = to_number)

但是我得到了

  

'where子句'中的未知列'tada_prod.sent_txts.to_number'

如果我注释掉查询运行正常。

这是sent_txts表

CREATE TABLE `sent_txts` (
  `id` int(64) NOT NULL AUTO_INCREMENT,
  `msg_link_id` int(64) DEFAULT NULL,
  `msg_class` varchar(256) DEFAULT NULL,
  `msg_ref` varchar(256) DEFAULT NULL,
  `to_number` varchar(256) DEFAULT NULL,
  `msg_body` text,
  `waiting_for_reply` int(64) DEFAULT NULL,
  `status` varchar(256) DEFAULT NULL,
  `tada_error` int(64) DEFAULT NULL,
  `msg_sent_datetime` datetime DEFAULT NULL,
  `reply_type` int(11) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=256379 DEFAULT CHARSET=utf8

很明显,专栏就在那里。

问题是什么?

<小时/> 以下是Jonathan

发布的查询说明
id  select_type  table  type  possible_keys  key  key_len  ref  rows    Extra                           
1   SIMPLE       a      ALL                                     10895                                   
1   SIMPLE       s      ALL                                     256050  Using where; Using join buffer  

以下是action_6_members的节目制作:

CREATE TABLE `action_6_members` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `draw_id` int(11) NOT NULL,
  `mobile` varchar(255) NOT NULL,
  `fly_buys` varchar(255) NOT NULL,
  `signup_date` datetime NOT NULL,
  `club` int(11) NOT NULL DEFAULT '0' COMMENT '1 = yes, 2 = no',
  `code` varchar(7) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=10896 DEFAULT CHARSET=latin1

1 个答案:

答案 0 :(得分:1)

通常,HAVING子句将聚合与值或另一个聚合相关联。问题的HAVING子句中的内容应该在主要的WHERE子句中:

SELECT COUNT(DISTINCT to_number) AS errors
  FROM sent_txts AS s
 WHERE msg_link_id = 0
   AND msg_sent_datetime BETWEEN '2010-08-09 07:00:00'
                             AND '2010-09-07 11:59:59'
   AND to_number IN (SELECT mobile FROM action_6_members AS a
                      WHERE a.mobile = s.to_number)

但你应该把它变成一个普通的连接:

SELECT COUNT(DISTINCT s.to_number) AS errors
  FROM sent_txts AS s
  JOIN action_6_members AS a ON a.mobile = s.to_number
 WHERE s.msg_link_id = 0
   AND s.msg_sent_datetime BETWEEN '2010-08-09 07:00:00'
                               AND '2010-09-07 11:59:59';