查询sql以从另一个表中查找行的计数

时间:2015-09-30 18:26:14

标签: mysql sql join

在我的MySQL数据库中,我有这3个表:

ACCOUNT (primary key is name)
 name
 directory
 birthdate
 sex

FILES (primary key is id)
 id (autoincrement)
 name (account foreign key)
 filename
 uploaded_date

CHECKED (primary key is the couple name - filename)
 name (account foreign key)
 filename (files foreign key)

我想创建一个显示结果表的查询:

RESULT
 name - directory - birthdate - sex - filename uploaded_date - checkedCount

在checkedCount列中,我希望在CHECKED表中为每个唯一文件名提供现有行的计数。

我试过这个,但我没有成功:

SELECT * FROM (SELECT * FROM account NATURAL JOIN files) AS table_alias LEFT JOIN (SELECT *, count(*) AS checkedCount FROM checked) AS checked_alias ON table_alias.filename = checked_alias.filename

目前在ACCOUNT表中只有2行,在FILES表中有6行,在CHECKED表中有6行具有来自ACCOUNT的相同名称,其他所有来自FILES的6个唯一文件名。

我无法理解为什么在checkCount列的结果表中,我将所有值设置为null,除了设置为6的值。我的目标应该是使用checkedCount = 1的所有六行,因为FILES中的每个文件都是table在CHECK表中使用了一次。

3 个答案:

答案 0 :(得分:1)

所以我猜你知道count是如何运作的吗?通过使用计数,您需要group by子句。

示例:

SELECT count(name) as count, name FROM CHECKED GROUP BY name

现在问题就在于此。你有一个非常讨厌的联接,你想要指望。因此,让我们加入表,别名,然后对字段进行计数。

SELECT ACCOUNT.name AS name, ACCOUNT.directory AS directory, ACCOUNT.birthDate AS birthdate, ACCOUNT.sex AS sex, FILES.filename AS filename, FILES.uploaded_date AS uploaded_date, count(CHECKED.filename) AS checkedCount
FROM ACCOUNT JOIN FILES ON ACCOUNT.name = FILES.name JOIN CHECKED ON FILES.filename = CHECKED.filename GROUP BY CHECKED.filename;

这......大......长......令人困惑......加入声明应该做你想做的事,但我也会看看MySQL CountMySQL Aliasing让事情变得更漂亮

答案 1 :(得分:1)

试试这个

SELECT
    a.*, f.filename, f.uploaded_date, IFNULL(c.cnt, 0) as 'checkedCount'
FROM
    account a
    LEFT OUTER JOIN files f ON a.name = f.name
    LEFT OUTER JOIN (SELECT name, COUNT(*) FROM checked GROUP BY 1) c ON a.name=c.name

答案 2 :(得分:0)

如果我直截了当,下面的godê应该适合你:

SELECT 
 A.name
,A.directory
,A.birthdate
,A.sexfilename
,F.uploaded_date
,(CASE WHEN C.filename IS NOT NULL THEN 1 ELSE 0 END) AS checkedCount
FROM 
ACCOUNT A
LEFT JOIN FILES F
     ON  A.name = F.name
LEFT JOIN CHECKED C
     ON F.filename = C.filename

尝试一下,让我知道。

我不知道你的数据库是什么,但是你的“CHECKED”表不能转换成FILES表中的“checked”列吗?因为它是1-1的关系?也许这会让事情变得更容易。