MySQL JOIN和GROUP BY

时间:2017-06-06 12:45:55

标签: mysql group-by

我应该得到1,因为对象3有一个超过零的属性(a3)。由于groupref连接(需要),我得到3。 我试图分组,但没有让它发挥作用。

简化陈述

SELECT COUNT(IF(a3 > 0, TRUE, NULL)) AS a3
FROM objects AS o 
LEFT JOIN attribs AS a ON o.id=a.oid 
LEFT JOIN group_ref AS gx ON gx.oid = o.id

缩减表格

attribs
------------
oid |   attrib  |   value
------------------------
1   |   a1  |   3
2   |   a2  |   0
3   |   a3  |   1


objects
------------
id  |   title
------------
1   |   obj1
2   |   obj2
3   |   obj3


groups
------------
id  |   title
------------
1   |   g1
2   |   g2
3   |   g3



group_ref
------------
gid |   oid
------------
1   |   1
1   |   2
2   |   1
3   |   3
3   |   2
3   |   1

2 个答案:

答案 0 :(得分:0)

这不是你想要的吗?

SELECT COUNT(*) AS a3 FROM attribs WHERE attrib = a3 HAVING value > 0

答案 1 :(得分:0)

也许这个

drop table if exists a1,o1,g1,gr1;

create table a1(oid int,   attribute varchar(20),    value int);
insert into a1 values
(1   ,   'a1'  ,   3),
(2   ,   'a2'  ,   0),
(3   ,   'a3'  ,   1);

create table o1(id  int,   title varchar(10));
insert into o1 values
(1   ,   'obj1'),
(2   ,   'obj2'),
(3   ,   'obj3');

create table g1(id  int,    title varchar(20));
insert into g1 values
(1   ,   'g1'),
(2   ,   'g2'),
(3   ,   'g3');

create table gr1(gid int,   oid int);
insert into gr1 values
(1   ,   1),
(1   ,   4),
(2   ,   1),
(3   ,   3),
(3   ,   4),
(3   ,   1);

SELECT o1.id,a1.attribute, 
         max(case when gr1.oid is not null then 1 else 0 end) as obs
FROM o1 
LEFT JOIN a1 ON o1.id=a1.oid 
LEFT JOIN gr1 ON gr1.oid = o1.id
group by o1.id,a1.attribute;

结果

+------+-----------+------+
| id   | attribute | obs  |
+------+-----------+------+
|    1 | a1        |    1 |
|    2 | a2        |    0 |
|    3 | a3        |    1 |
+------+-----------+------+
3 rows in set (0.00 sec)