1

我有三个实体: Cue(id, name) Reaction(id, name) Freqs(id, cue_id FK, reaction_id FK, some_other_data)

我想计算(cue,reaction)对的数量,比如(cue.name,reaction.name,count)我已经写了一个查询

SELECT
  a.cue_id, 
  a.reaction_id,
  Count(*) as freq
FROM 
  rdb_freqs a 
  JOIN rdb_reaction b ON a.cue_id=b.id
  JOIN rdb_cue c ON a.reaction_id=c.id
GROUP BY a.cue_id, a.reaction_id
ORDER BY freq DESC;

但是我应该如何用'name'替换'id'?

4

3 回答 3

3
SELECT distinct
  c.name cue_name,
  b.name reaction_name, 

 (SELECT
  Count(*)
  FROM 
  rdb_freqs a1
  where 
  a1.cue_id =  a.cue_id and 
  a1.reaction_id = a.reaction_id 
  ) as count
FROM 
  rdb_freqs a 
  inner JOIN rdb_reaction b ON a.reaction_id = b.id
  inner JOIN rdb_cue c ON a.cue_id = c.id
  order by count desc

SQLfiddle 示例(用 oracle 编写)

于 2013-11-05T20:28:26.477 回答
0
SELECT
FROM rdb_freq f
INNER JOIN (
    SELECT
      a.cue_id, 
      a.reaction_id,
      Count(*) as freq
    FROM 
      rdb_freqs a 
      JOIN rdb_reaction b ON a.cue_id=b.id
      JOIN rdb_cue c ON a.reaction_id=c.id
    GROUP BY a.cue_id, a.reaction_id
        ) AS tot ON f.cue_id = tot.cue_id
    INNER JOIN reaction
于 2013-11-05T17:50:22.837 回答
0
SELECT
  c.name as cue_name,
  b.name as reacion_name,
  Count(*) as freq
FROM 
  rdb_freqs a 
  JOIN rdb_reaction b ON a.cue_id=b.id
  JOIN rdb_cue c ON a.reaction_id=c.id
GROUP BY c.name, b.name
ORDER BY freq DESC;
于 2013-11-05T17:41:11.223 回答