需要帮助创建SQL查询

时间:2012-06-12 21:30:50

标签: mysql sql

我有两张桌子:

 CREATE TABLE `workers` (
  `id` int(7) NOT NULL AUTO_INCREMENT,
  `number` int(7) NOT NULL,
  `percent` int(3) NOT NULL,
  `order` int(7) NOT NULL,
      PRIMARY KEY (`id`)
 );
 CREATE `data` (
  `id` bigint(15) NOT NULL AUTO_INCREMENT,
  `workerId` int(7) NOT NULL,
  PRIMARY KEY (`id`)
 );

我想返回第一个工作人员(按order ASC排序)表示他的行数datapercent(来自表workers)/ 100小于number(来自表格workers

我试过这个问题:

SELECT workers.id, COUNT(data.id) AS `countOfData`
FROM `workers` as workers, `data` as data
WHERE data.workerId = workers.id
   AND workers.percent * `countOfData` < workers.number
LIMIT 1

但我收到错误:

#1054 - Unknown column 'countOfData' in 'where clause'

2 个答案:

答案 0 :(得分:1)

这应该有效:

SELECT A.id
FROM workers A
LEFT JOIN (SELECT workerId, COUNT(*) AS Quant
            FROM data
            GROUP BY workerId) B
ON A.id = B.workerId
WHERE (COALESCE(Quant,0) * `percent`)/100 < `number`
ORDER BY `order`
LIMIT 1

答案 1 :(得分:0)

您可以计算子查询中每个工作人员的行数。子查询可以连接到worker表。如果您使用left join,则将考虑没有数据行的工作人员:

select  *
from    workers w
left join    
        (
        select  workerId
        ,       count(*) as cnt
        from    data
        group by
                workerId
        ) d
on      w.id = d.workerId
where   coalesce(d.cnt, 0) * w.percent / 100 < w.number
order by
        w.order
limit   1