多次用外键计数子表

时间:2018-12-01 07:26:41

标签: mysql codeigniter

我有两个表

  1. 标签-> ID,名称,描述,用户,状态
  2. 标签连接。 -> ID,Label_id,类别

所以有多个类别,比如说1 =>新的,2 =>旧的。

我需要根据类别对子表进行计数。

这就是我现在拥有的,

SELECT `L`.*, COUNT(DISTINCT LC1.id) as count1, COUNT(DISTINCT LC2.id) as count2 
FROM (`Labels` L) 
LEFT JOIN `Label_connection` LC1 ON `LC1`.`Label_id` = `L`.`id` AND LC1.categories = "1" 
LEFT JOIN `Label_connection` LC2 ON `LC2`.`Label_id` = `L`.`id` AND LC2.categories = "2" 
WHERE `L`.`status` = '0' AND `L`.`user` = 1
GROUP BY `L`.`id` 
ORDER BY `L`.`id` DESC 
LIMIT 20

这确实使我能够正确地进行计数,但是我担心多个联接,因为类别数量会增加。

如果有人可以改善这一点,我将不胜感激,

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以尝试使用条件聚合将其写为一个JOIN

SELECT `L`.*
     , SUM(CASE WHEN LC.categories = "1" THEN 1 END) as count1
     , SUM(CASE WHEN LC.categories = "2" THEN 1 END) as count2
FROM `Labels` L
LEFT JOIN `Label_connection` LC ON `LC`.`Label_id` = `L`.`id`
WHERE `L`.`status` = '0' AND `L`.`user` = 1
GROUP BY `L`.`id` 
ORDER BY `L`.`id` DESC 
LIMIT 20

答案 1 :(得分:1)

对于条件聚合,您还可以使用COUNT DISTINCT .. CASE..WHEN..END

此外,您当前的查询无效GROUP BY(除非L.id是主键)。有关详细信息,请阅读:Error related to only_full_group_by when executing a query in MySql

此外,请更喜欢在字符串文字周围使用SQL-Standard单引号,而不是双引号。

SELECT L.id,  
       COUNT(DISTINCT CASE WHEN LC.categories = '1' THEN LC.id END) AS count1, 
       COUNT(DISTINCT CASE WHEN LC.categories = '2' THEN LC.id END) AS count2 
FROM Labels AS L
LEFT JOIN Label_connection AS LC 
  ON LC.Label_id = L.id
WHERE L.status = '0' AND
      L.user = 1
GROUP BY L.id 
ORDER BY L.id DESC 
LIMIT 20