2015-10-01 67 views
0

我有两个表SQL连接两个表having子句

First_id | Text Second_id | First_id | Date | Email 

我需要从具有计数第一个表中的所有记录从第二表日期空和电子邮件空。

我有SQL:

Select * from first f join second s on f.id = s.first_id where date is null and email is null group by first_id having(count(s.id) < 10 or count(s.id) = 0) 

它运作良好,但在那里我充满对第二台从第一个表ID的所有数据和电子邮件我没有结果。

的样本数据: 一台

1 | one 
2 | two 

二表

1 | 1 | NULL | NULL 
1 | 1 | 2015-01-01 | NULL 
1 | 2 | 2015-01-01 | NULL 
1 | 2 | 2015-01-01 | NULL 

我期望输出:

1 | one | 1 
2 | two | 0 

最后一列是项目的数量从第二的日期和电子邮件空值。我的查询返回

1 | one | 1 

没有第二排

+0

*“我需要从具有计数第一个表中的所有记录从第二表日期空和电子邮件空”。*:我不明白。那么你想要准确计算什么?考虑张贴样本输入和输出数据来澄清您的问题。 – sstan

回答

2

做一个左连接,也这是很好的指定要显示的列,否则你将得到重复。

Select * from first f left join second s on f.id = s.first_id where date is null and email is null group by first_id having(count(s.id) < 10 or count(s.id) = 0) 

看看这个图片,以了解如何加入工作:

http://i.stack.imgur.com/udQpD.jpg

+1

图片+1(真棒venn图) –

+0

没关系,但它不显示计数器的行数= 0 – Chris

0
SELECT t1.First_id, t2.Second_id 
FROM t1 
LEFT JOIN t2 
ON t1.First_id = t2.First_id 
INNER JOIN (
    SELECT Second_id 
    FROM t2 
    GROUP BY Second_id 
    HAVING (COUNT(*) < 10 OR COUNT(*) = 0) 
) _cc 
ON t.Second_id = _cc.Second_id 
WHERE t2.date IS NULL AND t2.email IS NULL; 

一个解决办法是检查HAVING限制在返回你需要休息加入ID的子查询。

当您使用GROUP BY语句时,只选择GROUP BY列或聚合函数,否则可能会产生不可预测的结果。

https://dev.mysql.com/doc/refman/5.1/en/group-by-handling.html

T-SQL GROUP BY: Best way to include other grouped columns