2017-06-06 226 views
0

我應該得到1作爲結果,因爲對象3有一個超過零的屬性(a3)。由於groupref加入(這是必要的)我得到3. 我試圖分組,但沒有得到它的工作。MySQL JOIN和GROUP BY

減少聲明

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 

回答

0

難道這不是你想要的?

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

的基本結構有留下來,因爲真正的查詢要大得多。 – Mike

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) 
+0

以某種方式沒有給我正確的結果 – Mike

+0

你能告訴我你的轉錄代碼嗎? –