我有两个 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 语句编写,那就太好了。
非常感谢。