有一个MySQL 表:
+----+-------+------+------------+---------+
| id | name | type | date | deleted |
+----+-------+------+------------+---------+
| 1 | nameA | 1 | 2016:10:15 | 1 |
+----+-------+------+------------+---------+
| 2 | nameB | 1 | 2016:10:20 | 0 |
+----+-------+------+------------+---------+
| 3 | nameC | 2 | 2016:09:26 | 0 |
+----+-------+------+------------+---------+
| 4 | nameD | 2 | 2016:09:30 | 0 |
+----+-------+------+------------+---------+
| 5 | nameE | 3 | 2016:09:26 | 0 |
+----+-------+------+------------+---------+
我想SELECT
除了删除= 1之外的所有内容,除非type = 2的日期早于今天(2016:09:27)。所以我尝试使用NOT IN
,但我这样做也排除了type = 3,它的日期比今天早:
$currentDate = date("Y:m:d");
$sql = "SELECT * FROM table WHERE deleted != 1 AND date NOT IN
(SELECT date FROM table WHERE type = 2 AND date < '$currentDate') ORDER BY date";
有任何帮助吗?谢谢!
答案 0 :(得分:0)
试试这样:
$sql = "SELECT * FROM table WHERE deleted = 0 AND NOT (type = 2 AND date < DATE(NOW())) ORDER BY date";
我认为你不需要在PHP中定义currentDate。
答案 1 :(得分:0)
使用Str_to_date
SELECT * FROM table
WHERE deleted != 1
AND date NOT IN
(SELECT date FROM table
WHERE type = 2 AND str_to_date(date, '%Y:%m:%d' ) < curdate())
ORDER BY str_to_date(date", '%Y:%m:%d')
答案 2 :(得分:0)
您的数据库结构存在根本性错误。
如果要有效地比较日期和时间,则需要使用适当的数据类型Nullable
。不要使用字符串--MySQL无法告诉如何订购结果或更低或更高的结果。
将类型更改为DATETIME
并形成您的查询,如:
DATETIME
如果您根本不想使用时间,请使用WHERE datetime_column < DATE_SUB(CURDATE(), INTERVAL 1 DAY)
代替DATE
。
答案 3 :(得分:0)
表格结构:
CREATE TABLE `example` (
`id` int(11) DEFAULT NULL,
`name` varchar(30) DEFAULT NULL,
`type` int(11) DEFAULT NULL,
`date` date DEFAULT NULL,
`deleted` int(11) DEFAULT NULL
)
/*Data for the table `example` */
insert into `example`(`id`,`name`,`type`,`date`,`deleted`) values (1,'nameA',1,'2016-10-15',1),(2,'nameB',1,'2016-10-20',0),(3,'nameC',2,'2016-09-26',0),(4,'nameD',2,'2016-09-30',0),(5,'nameE',3,'2016-09-28',0),(6,'nameE',3,'2016-09-26',0);
必填查询:
SELECT * FROM EXAMPLE WHERE (deleted != 1 AND id NOT IN (SELECT id FROM EXAMPLE WHERE (TYPE = 2 AND DATE < CURDATE()))) ORDER BY DATE