0

I Have a table 'C' in MySQL db with the following structure:

Object1Id (int) - PK and has one to many relation to table 'A',

Object2Id (int) - PK and has one to many relation to table 'A',

OccuranceId (int) - FK and has one to many relation to table 'B'.

Basically table 'C' has many to many relation with table 'A' and one to many relation with table 'B'.

The data:

1, 3, 1
1, 3, 39
3, 1, 402
3, 1, 27
1, 3, 40
3, 1, 12

I try to group the records with the query:

SELECT CASE WHEN least(Object1Id, Object2Id) = Object1Id THEN Object1Id ELSE Object2Id END AS Object1Id, 
       CASE WHEN Greatest(Object1Id, Object2Id) = Object2Id THEN Object2Id ELSE Object1Id END AS Object2Id, 
       count(OccuranceId) AS OccuranceCount
FROM 'C'
GROUP BY Object1Id, Object2Id

The result I get back from the query are:

1, 3, 3 - for object1Id = 1 and Object2Id = 3

1, 3, 3 - for Object1Id = 3 and Object2Id = 1

I would like the result to sum up as : 1, 3, 6

How can I produce the desired result?

Thanks.

4

2 に答える 2

0

First I would simplify the query to

SELECT least(Object1Id, Object2Id) AS Object1Id,
       Greatest(Object1Id, Object2Id) AS Object2Id,
       count(OccuranceId) AS OccuranceCount
FROM C
GROUP BY Object1Id, Object2Id

Your query doesn't work, because you have columns object1id and object2id and reuse these names for the result columns least() and greatest(). But the group by clause groups by the table columns not your result columns. When you rename the result columns to some other names, it works as you expect

SELECT least(Object1Id, Object2Id) AS least_val,
       Greatest(Object1Id, Object2Id) AS greatest_val,
       count(OccuranceId) AS OccuranceCount
FROM C
GROUP BY least_val, greatest_val

SQL Fiddle for testing

于 2012-12-04T09:10:26.670 に答える
0

yes!

SELECT Object1Id, Object2Id, sum(OccuranceCount)
FROM (

__ YOUR SELECT __

) foo 
于 2012-12-04T09:12:15.030 に答える