1

我有一个带有布尔列的下表,has_object它指示每一行是否有关联的数字对象。

+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| pid        | varchar(255) | NO   | PRI |         |       |
| title      | text         | YES  |     | NULL    |       |
| owner_uid  | int(11)      | YES  |     | NULL    |       |
| has_object | int(11)      | YES  |     | NULL    |       |
+------------+--------------+------+-----+---------+-------+

我已尝试使用此查询来获取有关每个owner_uid. 但在我的表中它返回错误的结果:

SELECT 
  a.owner_uid, 
  count(b.pid) as count1, 
  count(c.pid) as count2  
FROM
  islandora_report a
  JOIN islandora_report b ON b.owner_uid = a.owner_uid AND b.has_object = 0
  JOIN islandora_report c ON c.owner_uid = a.owner_uid AND c.has_object = 1
GROUP BY a.owner_uid;

结果:

在此处输入图像描述

4

3 回答 3

1

由于BOOLEAN只是一个0or 1,您实际上可以在SUM()没有任何连接的情况下执行一对来添加列。

SELECT
  owner_uid,
  /* SUM() adds up all the 1 values */
  SUM(has_object) AS count_true,
  /* Invert the boolean with a case statement to get the inverse */
  SUM(CASE WHEN has_object = 1 THEN 0 ELSE 1 END) AS count_false
FROM islandora_report
GROUP BY owner_uid

除了上述方法之外,还有其他方法可以反转布尔值。这只是第一个想到的。您还可以从总数中减去真实的总和,例如:

SUM(has_object) AS count_true,
COUNT(*) - SUM(has_object) AS count_false
于 2012-10-12T17:53:28.833 回答
1

您实际上并不需要连接;你可以写:

SELECT owner_uid,
       COUNT(CASE WHEN has_object = 0 THEN 1 END) AS count1,
       COUNT(CASE WHEN has_object = 1 THEN 1 END) AS count2
  FROM islandora_report
 GROUP
    BY owner_uid
;
于 2012-10-12T17:53:53.283 回答
1

怎么办:

SELECT
  owner_id, count(*), has_object = 1 as has_it
FROM islandora_report
GROUP BY owner_id,has_it
于 2012-10-12T18:01:54.023 回答