需要从MySQL表中获取某些条件不存在的值

时间:2012-03-30 14:47:53

标签: php mysql

SELECT DISTINCT monthly_returns.company_id
        FROM monthly_returns LEFT JOIN paidreturns ON monthly_returns.company_id = paidreturns.company_id
        WHERE NOT EXISTS (SELECT * FROM paidreturns WHERE paidreturns.company_id = monthly_returns.company_id
        AND paidreturns.month = '$cdate' and paidreturns.paid = 1)

表格结构:

CREATE TABLE IF NOT EXISTS `paidreturns` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `company_id` int(11) NOT NULL,
  `paid` tinyint(1) NOT NULL,
  `month` date NOT NULL,
  `total` decimal(9,2) NOT NULL,
  PRIMARY KEY (`id`)
)

CREATE TABLE IF NOT EXISTS `monthly_returns` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
  `company_id` int(11) NOT NULL,
  `employee_id` int(11) NOT NULL,
  `pay_week1` decimal(9,2) unsigned DEFAULT NULL,
  `pay_week2` decimal(9,2) unsigned DEFAULT NULL,
  `pay_week3` decimal(9,2) unsigned DEFAULT NULL,
  `pay_week4` decimal(9,2) unsigned DEFAULT NULL,
  `pay_week5` decimal(9,2) unsigned DEFAULT NULL,
  `pay_weeks` int(1) unsigned DEFAULT NULL,
  `month` date NOT NULL,
  PRIMARY KEY (`id`)

我正在努力获得一份本月尚未支付回报的公司名单。 我正在使用'NOT EXISTS'来实现这一目标,但我仍然得到一家公司已退回,并且本月有退货。 任何帮助表示赞赏...

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT DISTINCT 
      monthly_returns.company_id 
   FROM 
      monthly_returns 
         LEFT JOIN paidreturns 
            ON monthly_returns.company_id = paidreturns.company_id 
           AND paidreturns.month = '$cdate' 
           and paidreturns.paid = 1 
   WHERE 
      paidreturns.company_id IS NULL