sql - 这个内部查询(MySQL)有什么问题

标签 sql mysql

...除了我是一个完全业余的事实之外?

我的 table 是这样布置的:

CREATE TABLE `messages` (
 `id` int(6) unsigned NOT NULL AUTO_INCREMENT,
 `patient_id` int(6) unsigned NOT NULL,
 `message` varchar(255) NOT NULL,
 `savedate` int(10) unsigned NOT NULL,
 `senddate` int(10) unsigned NOT NULL,
 `SmsSid` varchar(40) NOT NULL COMMENT 'where we store the cookies
from twilio',
 `sendorder` tinyint(3) unsigned NOT NULL COMMENT 'the order we want
the msg sent in',
 `sent` tinyint(1) NOT NULL COMMENT '0=queued, 1=sent,
2=sent-unqueued,4=rec-unread,5=recd-read',
 PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=143 ;

我需要一个查询

SELECT * FROM `messages` WHERE `senddate` < $now AND `sent` = 0 (AND LIMIT
TO ONLY ONE RECORD PER `patient_id`)

我试过以下方法:

SELECT * 
FROM `messages`
WHERE `senddate` IN 
    (SELECT `patient_id`, max(`senddate`)
     GROUP by `patient_id`) 
AND `senddate` < $now AND `sent` = 0 ;

但是我得到这个错误: MySQL客户端版本:5.1.37

`#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP by patient_id) AND senddate < 1270093898 AND sent = 0 LIMIT 0, 30' at line 5

最佳答案

除了子查询中缺少 FROM 子句外,IN 子句还需要子查询中的单个列。您正在选择列。

将子查询更改为具有 FROM 子句并仅返回预期的列:

SELECT * 
FROM `messages`
WHERE `senddate` IN 
    (SELECT max(`senddate`)
     FROM `patients`
     GROUP by `patient_id`) 
AND `senddate` < $now AND `sent` = 0 ;

关于sql - 这个内部查询(MySQL)有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2560349/

相关文章:

sql - 哪个查询的性能更好?

MYSQL 对具有唯一结果的列求和

mysql | mysql |具体要求

sql - activerecord 中最近的内部查询

sql - 将两列数据合并为一列,留下空值

php - 如何将所有数组数据插入mysql?

mysql - 连接两个包含一个 WHERE 子句的 MySQL SELECT 语句

mysql - 为什么在 SQL 匹配中使用 'LIKE' 不算数?

php - 如何从jquery表中插入多个表单数据到数据库

sql - 如何更改 SQL 查询输出?