【问题标题】:How to get pairs from sqlite如何从 sqlite 获取对
【发布时间】:2015-11-24 22:42:30
【问题描述】:

我是一个数据库,我只是在为一个小组项目玩 sqlite3。

我有两张类似这样的表格:

Table 1:    
tv_show_id, tv_show_rating

Table 2:    
tv_show_id, cast_id

每个 tv_show 有 1 个唯一 id,但在表二中,每个 tv_show 有多个 cast_id

所以我们有这样的东西:

Table 1: 
1234, 90
5678, 88

Table 2:
1234, "person 1"
1234, "person 2"
5678, "person 1"
5678, "person 3"

我想要以下结果:(人 a,人 b,共显示 # 个)

(person 1, person 2, 1)
(person 1, person 3, 1)
(person 2, person 1, 1)
(person 2, person 3, 0)
(person 3, person 1, 1)
(person 3, person 2, 0)

如何使用 JOINS 获得这些结果?

【问题讨论】:

标签: sql database sqlite select join


【解决方案1】:

你可以试试这个。 Fiddle

select z.id,count(w.show_id) from
(
  select distinct concat(x.cid,',',x.did) as id
  from 
  (
   select tt.cast_id as cid,ttt.cast_id  as did
   from t2 tt,t2 ttt
   where tt.cast_id <> ttt.cast_id
   ) x
  left join t2  on x.cid = t2.cast_id
 ) z
left join (select show_id, group_concat(cast_id order by cast_id) cid
           from t2
           group by show_id
           union all 
           select show_id, group_concat(cast_id order by cast_id desc) cid
           from t2
           group by show_id
           ) w
on z.id = w.cid
group by z.id;

【讨论】:

    【解决方案2】:

    执行此操作的一种方法(这可能不是最聪明的)是使用交叉连接来创建一组所有可能的对,并使用连接和左连接来确定这对是否一起工作。

    在此查询中,您的源表称为table2

    select 
      cast1, 
      cast2, 
      sum(case when t2.cast_id is null then 0 else 1 end) as worked_together
    from (
      select distinct 
        t1.cast_id cast1, 
        t2.cast_id cast2 
      from table2 t1,table2 t2 
      where t1.cast_id != t2.cast_id
    ) p
    join table2 t1 on p.cast1 = t1.cast_id 
    left join table2 t2 on t1.show_id = t2.show_id 
                       and p.cast2 = t2.cast_id 
                       and t1.cast_id != t2.cast_id
    group by cast1, cast2;
    

    Sample SQL Fiddle(使用 SQL.js 测试)。该查询仅使用 ANSI SQL,并可移植到其他数据库。

    在其他一些数据库中,您可以使用 full outer join 完成此操作,但 SQLite 不支持该构造。

    【讨论】:

      猜你喜欢
      • 2019-10-09
      • 2015-09-15
      • 2012-10-10
      • 1970-01-01
      • 2021-12-15
      • 2011-03-19
      • 2011-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多