显示除4个子记录之外的所有父记录

时间:2012-08-05 08:37:15

标签: mysql sql

我需要显示父表中来自sql的记录,这些记录的子记录小于4或没有子记录,请点击SQL查询。

更多澄清:

  1. 根本没有父母的子记录也没关系,所有父记录都应显示
  2. 如果父记录的子记录介于1和3之间,则应显示
  3. 如果父记录恰好有4个子记录,则不应显示它。
  4. 架构(员工不得超过4次捐款)

    客户端(client_id,电子邮件)

    员工(employee_id,姓名)

    捐款(donation_id,employee_id,client_id)

    SQL我试过了。

    SELECT * FROM employee left join 
    (SELECT donation_id, employee_id, client_id, count(employee_id) as count from donation      GROUP BY employee_id HAVING count <= 4) as d
    ON employee.employee_id = d.employee_id
    

3 个答案:

答案 0 :(得分:0)

SELECT    a.employee_id, a.name
FROM      employee a
LEFT JOIN (
          SELECT   employee_id, COUNT(*) AS cnt
          FROM     donation
          GROUP BY employee_id
          ) b ON a.employee_id = b.employee_id
WHERE     b.cnt < 4 OR b.employee_id IS NULL

WHERE条款基本上只包括少于4个孩子(b.cnt < 4)或者根本没有孩子的父母(b.employee_id IS NULL)。

答案 1 :(得分:0)

SELECT e.* 
  FROM employee e 
  LEFT OUTER JOIN (
    SELECT employee_id, count(parent_id) c 
    FROM donation
    GROUP BY employee_id
  ) s 
  ON s.employee_id = employee_id 
  WHERE s.c < 4 OR s.c IS NULL

并添加此索引

CREATE INDEX idx_employee_id ON donation (employee_id)

答案 2 :(得分:0)

您可以按员工加入表格,并为少于4条记录的人筛选组:

SELECT   employee.*
FROM     employee LEFT JOIN donation USING (employee_id)
GROUP BY employee_id
HAVING   COUNT(*) < 4