我有3个表,定义如下。 (文件夹和地址簿条目,连接表中的连接为1:多表。地址簿可以在多个文件夹中)
我正在尝试获取文件夹列表,这很容易。 我添加了COUNT(总数)文件夹中有多少条目,这也很容易。
但是我还需要添加另外一个COUNT,其中COUNT(总数)中有多少人的addressbook_lastchecked为0
所以或多或少我需要计算该文件夹中的总名称数,然后再计算其中有多少总数未经检查...
**addressbook**
addressbook_id
addressbook_lastchecked
addressbook_name
**folders**
folder_id
folder_name
**folders_connections**
connection_id
folder_id
addressbook_id
到目前为止我的努力..我需要选择不选择吗?
SELECT f . * , c.lastchecked, COUNT( c.lastchecked ) AS entries
FROM folders AS f
LEFT JOIN (
SELECT fc.folder_id, a.lastchecked
FROM folder_connections AS fc
LEFT JOIN addressbook AS a
USING ( addressbook_id )
WHERE a.lastchecked =0
) AS c
USING ( folder_id )
我的额外努力是(这是不正确的,因为它有重复。)
SELECT f.*, COUNT(c.connection_id) AS entries, COUNT(csub.connection_id) AS unchecked
FROM folders AS f
LEFT JOIN folder_connections AS c USING(folder_id)
LEFT JOIN (SELECT fc.*, ab.lastchecked FROM folder_connections AS fc
LEFT JOIN addressbook AS ab USING(addressbook_id) WHERE ab.lastchecked=0) AS csub USING(folder_id)
GROUP BY c.folder_id ORDER BY folder_name Asc LIMIT 0, 15
通过混合两件事来解决。
SELECT f.folder_id, f.folder_name, SUM(
CASE c.lastchecked
WHEN 0
THEN 1
ELSE 0
END ) AS unchecked, COUNT( c.lastchecked ) AS entries
FROM folders AS f
LEFT JOIN (
SELECT fc.folder_id, a.lastchecked
FROM folder_connections AS fc
INNER JOIN addressbook AS a
USING ( addressbook_id )
)c
USING ( folder_id )
GROUP BY f.folder_id, f.folder_name
LIMIT 0 , 30
答案 0 :(得分:1)
在我理解的范围内是解决方案:
首先选择addressbook_lastchecked is 0
SELECT fc.folder_id, a.lastchecked
FROM folder_connections AS fc
Inner JOIN addressbook AS a // Inner join is a best option as you get all folders
USING ( addressbook_id )
WHERE a.lastchecked =0
//现在您拥有所有上次检查的文件夹0
现在通过组合两个查询来计算文件夹数和最后检查数。
SELECT f . folder_id,f.folder_name
, count(c.lastchecked) checkedcount, COUNT( c.lastchecked ) AS entries
FROM folders AS f left join ( SELECT fc.folder_id, a.lastchecked
FROM folder_connections AS fc
Inner JOIN addressbook AS a // Inner join is a best option as you get all folders
USING ( addressbook_id )
WHERE a.lastchecked =0) c
USING ( folder_id )
group by f . folder_id,f.folder_name
现在你有文件夹ID和相应的计数和检查计数。
如果您不是在寻找,请告诉我。