2011-02-23 40 views
1

我有一个表的设置如下:SQL订单价值

+---------------+ 
| resources  | 
+---------------+ 
| id   | 
| name   | 
+---------------+ 
+-------------------+ 
| resource_subjects | 
+-------------------+ 
| resource_id  | 
| subject_id  | 
+-------------------+ 

我需要做的是建立其发现两个资源之间共享的对象的数目的查询。

所以有resource_subjects表是这样的:

+---------------------------+ 
| resource_id | subject_id | 
+---------------------------+ 
| resource1 | 1   | 
| resource1 | 2   | 
| resource1 | 3   | 
| resource1 | 4   | 
| resource1 | 5   | 
| resource2 | 1   | 
| resource2 | 2   | 
| resource2 | 3   | 
| resource3 | 1   | 
| resource3 | 4   | 
+---------------------------+ 

我想这个查询给我这样的:

+----------------------------------------------------------+ 
| first_resource | second_resource | shared_subjects_count | 
+----------------------------------------------------------+ 
| resource1  | resource2  | 3      | 
| resource1  | resource3  | 2      | 
| resource2  | resource3  | 1      | 
+----------------------------------------------------------+ 

要跨的想法,伪代码在我头部会读取类似:

选择id AS first_resourceid AS second_resource,COUNT(受试者 数first_resource和second_resource在resource_subjects表之间共享)AS shared_subjects_count ORDER BY shared_subjects_count DESC

如果任何人都可以提供一个示例查询,或者甚至点我在正确的方向那d太棒了。

感谢

回答

0

创建一个类似于你我用一个表:

CREATE TABLE resource_subjects (
res_id int(11), 
sub_id int(11) 
); 

INSERT INTO resource_subjects VALUES 
(1,1), 
(1,2), 
(1,3), 
(1,4), 
(1,5), 
(2,1), 
(2,2), 
(2,3), 
(3,1), 
(3,4); 

然后你就可以使用查询:

SELECT t2.res_id 'first', t1.res_id 'second', COUNT(t1.sub_id) 
FROM resource_subjects t1 
JOIN resource_subjects t2 ON t1.res_id > t2.res_id AND t1.sub_id = t2.sub_id 
GROUP BY 1,2 

注意,我RESOURCE_ID是一个真正的ID (整数)而不是一个字符串,它允许ON子句中的条件大于条件。

+0

RESOURCE_ID是在我的情况一个int,我只是用资源1,资源2等的可读性(应该澄清)。谢谢你的回答,很有魅力。 – Paul 2011-02-23 10:08:53

0

这似乎在MySQL的:

select 
    a.resource_id as first_resource, 
    b.resource_id as second_resource, 
    count(*) as shared_subjects_count 

from 
    resource_subjects as a, 
    resource_subjects as b 

where 
    a.resource_id < b.resource_id 
    and a.subject_id = b.subject_id 
    group by a.resource_id,b.resource_id; 
+0

没有'ORDER BY'子句......? – onedaywhen 2011-02-23 10:23:19