2

我有两个 PostgreSQL 语句,我想在我的 RoR 应用程序中组合它们。

第一个 SQL 语句返回一个链接,该链接包含两个特定的 tag_id。

SELECT link_id, count(*) as counter
  FROM "totals"
 WHERE "totals"."tag_id" IN (6, 8)
   AND (score > 0)
 GROUP BY link_id
HAVING count(*)=2

RoR ActiveRecord 版本:

 links = Total.find_all_by_tag_id(@tag_list, :conditions => ["score > 0"], :select => "link_id, count(*) as counter", :having => "count(*)=#{@tag_list.count}", :group => "link_id").collect(&:link_id).uniq.sort.reverse

第二条 SQL 语句返回特定 tag_id 得分最高的链接。

SELECT s1.link_id
  FROM totals AS s1
     , (SELECT link_id
              , MAX(score) AS maxscore
          FROM totals
         GROUP BY link_id) as s2
 WHERE s2.link_id = s1.link_id
   and s1.score = s2.maxscore
   AND s1.score > 0 AND s1.tag_id = 6

该表的构造如下:

totals:
  link_id : integer
  tag_id : integer
  score : integer

=============================
| link_id  | tag_id | score |
=============================
|    1     |    6   |   5   |
|    1     |    8   |   2   |
|    1     |    3   |   1   |
|    2     |    6   |   6   |
|    2     |    4   |   2   |
|    2     |    8   |   6   |
|    3     |    6   |   5   |
|    3     |    2   |   4   |
|    4     |    2   |   4   |
|    4     |    6   |   1   |
|    4     |    8   |   2   |
=============================

第一个 SQL 语句将返回link_ids 1, 2 and 4,第二个 SQL 语句将返回link_ids 1, 2 and 3

如何将两条 SQL 语句合二为一,以便获得包含多个选定标签的特定标签的最高分?

组合语句应返回link_ids 1 and 2.

DDL 和 INSERT 命令可以在这里找到:http ://sqlize.com/480glD5Is4

如果这可以用 RoR ActiveRecord 样式或更优化的 SQL 语句编写,那就太好了。

非常感谢。

4

1 回答 1

1

第一个 SQL 语句返回一个链接,该链接包含两个特定的 tag_id。

当且仅当 {link_id, tag_id} 上存在主键约束或唯一约束时才有效。我添加了该约束(有意义),我将为其他人添加 CREATE TABLE 和 INSERT 语句。(您应该这样做。您可以编辑您的问题并根据需要粘贴这些内容。)

create table totals (
  link_id  integer not null,
  tag_id integer not null,
  score integer not null,
  primary key (link_id, tag_id)
);

insert into totals values
(1, 6, 5   ),
(1, 8, 2   ),
(1, 3, 1   ),
(2, 6, 6   ),
(2, 4, 2   ),
(3, 6, 1   ),
(3, 2, 4   ),
(3, 8, 3   ),
(4, 2, 4   ),
(4, 6, 1   ),
(4, 8, 2   );

根据评论重新表述问题,您正在寻找具有

  • 标签 ID 编号为 6 和 8,并且
  • 标签 id 6 的分数高于标签 id 8 的分数

首先,很容易看出这两个查询会给你分数

  • 所有 tag_id = 6 的行,以及
  • tag_id = 8 的所有行

    select *
    from totals
    where tag_id = 6
    
    select *
    from totals
    where tag_id = 8
    

这很简单。

我们可以使用公共表表达式轻松连接这两个查询。

with score_for_8 as (
  select *
  from totals
  where tag_id = 8
) 
select totals.* 
from totals 
inner join score_for_8
        on score_for_8.link_id = totals.link_id and
           totals.score > score_for_8.score 
where totals.tag_id = 6;

由于这不需要对结果集进行分组、排序或限制,因此它将正确报告平局。

我很确定这仍然不是您想要的,但我不明白您的最后评论。

于 2011-11-19T15:54:57.360 回答