Sqlite双重左外连接与计数

时间:2014-06-11 16:39:14

标签: sqlite count left-join

我有以下数据库结构:

  • tbl_record(_id,_id_user,...)
  • tbl_photo(_id,_id_record,...)
  • tbl_note(_id,_id_record,...)

在计算记录所拥有的照片数量时列出特定用户的记录时,我使用以下查询,该工作正常:

SELECT tbl_record._id, COUNT(tbl_photo._id_record) AS photo_count FROM tbl_record
   LEFT OUTER JOIN tbl_photo ON tbl_record._id=tbl_photo._id_record
WHERE tbl_record._id_user=? GROUP BY tbl_record._id;

现在,我想像上面那样做,但也要计算记录的笔记数量:

SELECT tbl_record._id, COUNT(tbl_photo._id_record) AS photo_count, COUNT(tbl_note._id_record) AS note_count FROM tbl_record
   LEFT OUTER JOIN tbl_photo ON tbl_record._id=tbl_photo._id_record
   LEFT OUTER JOIN tbl_note ON tbl_record._id=tbl_note._id_record
WHERE tbl_record._id_user=? GROUP BY tbl_record._id;

当记录包含> 0张照片时,第二个查询的计数无法正常工作> 0个音符,例如3张照片& 5张照片,每张照片的计数为15(3 * 5)。

知道如何让第二个查询返回正确的计数吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用COUNT(DISTINCT some_id)过滤掉重复项,但这样效率很低。 更好地使用相关子查询:

SELECT _id,
       (SELECT COUNT(*)
        FROM tbl_photo
        WHERE _id_record = tbl_record._id
       ) AS photo_count,
       (SELECT COUNT(*)
        FROM tbl_note
        WHERE _id_record = tbl_record._id
       ) AS note_count
FROM tbl_record
WHERE _id_user = ?