我有 2 个表,任务和报价,一旦公司(企业)没有提供报价,我想选择所有任务。我已经为这两个表和一些示例数据包含了 SQL。我的查询如下所示,但它不起作用。
询问:
SELECT
`task`.`id`,
`task`.`carid`,
`task`.`duedate`,
`task`.`categoryid`,
`task`.`offers`
FROM
`task`
LEFT JOIN
`offer`
ON
`task`.`id` = `offer`.`taskid`
WHERE
`task`.`offers` < 3
AND
`offer`.`businessid` != 16
ORDER BY
`task`.`id` DESC
表:
CREATE TABLE `task` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`carid` int(10) NOT NULL,
`duedate` date NOT NULL,
`categoryid` int(10) NOT NULL,
`offers` int(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
INDEX `carid` USING BTREE (carid),
INDEX `categoryid` USING BTREE (categoryid)
) ENGINE=`InnoDB` AUTO_INCREMENT=3 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ROW_FORMAT=COMPACT CHECKSUM=0 DELAY_KEY_WRITE=0;
CREATE TABLE `offer` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`businessid` int(10) NOT NULL,
`taskid` int(10) NOT NULL,
`price` decimal(10,2) NOT NULL,
`status` enum('received','rejected','accepted','completed') NOT NULL DEFAULT 'received',
PRIMARY KEY (`id`),
INDEX `businessid` USING BTREE (businessid),
INDEX `taskid` USING BTREE (taskid)
) ENGINE=`InnoDB` AUTO_INCREMENT=2 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ROW_FORMAT=COMPACT CHECKSUM=0 DELAY_KEY_WRITE=0;
样本数据:
insert into `task` (1, 1, "2012-09-30", 3, 0);
insert into `task` (2, 1, "2012-09-27", 5, 0);
insert into `offer`(1, 16, 1, 3000, "received");
insert into `offer`(2, 13, 2, 212, "received");
insert into `offer`(3, 16, 2, 23, "received");
我想我现在可能已经解决了:
SELECT
`task`.`id`,
`task`.`carid`,
`task`.`categoryid`,
`task`.`duedate`,
`task`.`offers`
FROM
task
LEFT JOIN
`offer`
ON
`task`.`id` = `offer`.`taskid`
WHERE
task.id NOT IN (
SELECT
`offer`.`taskid`
FROM
`offer`
WHERE
`offer`.`businessid` = 16
)
OR
businessid IS NULL
AND
offers < 3
GROUP BY
task.id
ORDER BY
duedate ASC