使用来自3个表MySQL的数据查找总行数

时间:2013-12-28 01:38:58

标签: mysql sql select join distinct

我正在尝试返回一个数字,但我认为查询需要覆盖3个表格! 这里有一个快速的例子,说明3个表是如何切断的(有几列被切断)

table: opencall
---------------------------------
Users name | Site  | Phone      |
---------------------------------
John Smith | Leeds | 0113 1234567

table: userdb
-------------------------------------
emailAd         | site  | company   |
-------------------------------------
user@domain.com | Leeds | Yorks Post

table: company
----------------------------
pk_company_id  | division_name |
----------------------------
Yorks Post     | NORTH

现在,我要做的是在opencall中找到“division_name”为“NORTH”的行总数,我尝试了几个查询,但是它们总是会返回一个数字太大的数字。

这是我尝试过的一个例子:

SELECT count(*) FROM opencall, company, userdb WHERE userdb.site = opencall.site AND userdb.company = company.pk_company_id AND opencall.logdatex BETWEEN 1385041200 and 1388041200 AND opencall.condition NOT IN (8,9,11,12,19) AND company.division_name = 'NORTH`'

然而,这会返回超过8,000的结果,就好像我只是把:

SELECT count(*) FROM opencall where logdatex BETWEEN 1385041200 and 1388041200 AND condition NOT IN (8,9,11,12,19)

这会返回128,所以我在限制division_name时所遵循的数字应该是20左右。任何对此的帮助都将非常感激。

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT COUNT(DISTINCT oc.UsersName)
FROM opencall oc 
INNER JOIN userdb u ON oc.site = u.site
INNER JOIN company c ON u.company = c.pk_company_id
WHERE c.division_name = 'NORTH'AND oc.logdatex BETWEEN 1385041200 AND 1388041200 AND 
      oc.condition NOT IN (8,9,11,12,19)

答案 1 :(得分:0)

您的数据结构搞砸了。公司和部门之间没有联系。您可以使用聚合从userdb创建一个。我认为这样做你想要的:

SELECT count(*)
FROM (select distinct site, company
      from userdb u
     ) u join
     opencall o
     on u.site = o.site join
     company c
     on u.company = c.pk_company_id
WHERE o.logdatex BETWEEN 1385041200 and 1388041200 AND
      o.condition NOT IN (8,9,11,12,19) AND
      c.division_name = 'NORTH`;