【问题标题】:How to accumulate matches when querying multiple tables in SQLite?在 SQLite 中查询多个表时如何累积匹配?
【发布时间】:2021-01-07 01:52:23
【问题描述】:

表1

ID     Name     CourseID
1     Course 1   4002
2     Course 2   2342
3     Course 3   2410 

表2

CourseID ProfName
4002     John
2342     bob 
2410     Bill
4002     Hannah
2342     Cyrus 

当我尝试时

SELECT ID, Name, CourseID, ProfName 
FROM Table1, Table2
WHERE Table1.CourseID = Table2.CourseID 

我得到了返回相同 CourseID 的多个实例,这样当我打印出来时

“1,课程 1,4002,约翰”和

“1, Course 1, 4002, Hannah”是两个不同的输出。

我希望它们具有以下形式

“1,课程 1,4002,约翰和汉娜

不确定如何更改我的 SQL 查询来实现这一点?

【问题讨论】:

  • 如果你有超过 2 个呢?
  • 我想显示完整列表,例如“John, Hannah, Sarah, Joshua”等
  • 请在代码问题中给出minimal reproducible example--cut & paste & runnable code,包括最小的代表性示例输入作为代码;期望和实际输出(包括逐字错误消息);标签和版本;明确的规范和解释。给出尽可能少的代码,即您显示的代码可以通过您显示的代码扩展为不正常的代码。 (调试基础。)对于包含 DBMS 和 DDL(包括约束和索引)和输入为格式化为表的代码的 SQL。 How to Ask 暂停总体目标的工作,将代码砍到第一个表达式,没有给出你期望的内容,说出你期望的内容和原因。

标签: sql string sqlite group-by inner-join


【解决方案1】:

使用字符串聚合:

select t1.id, t1.name, t1.courseid, group_concat(t2.profname, ' and ') profnames
from table1 t1
inner join table2 t2 on t1.courseid = t2.courseid 
group by t1.id, t1.name, t1.courseid

请注意,这使用 标准 连接语法 (join ... on ...) 而不是隐式连接(在 from 子句中使用逗号):这种老式语法不应在新代码中使用.

你也可以使用子查询:

select t1.*
    (
        select group_concat(t2.profname, ' and ') 
        from table2 t2
        where t2.courseid = t1.courseid
    ) profnames
from table1 t1

无关注释:and 似乎不是列表分隔符的好选择:如果有两个以上的值,则结果不是正确的英文。例如,更常见的选择是逗号 (,) - 这是 SQLite 和大多数其他数据库中的默认分隔符。

【讨论】:

    【解决方案2】:

    我猜您希望在大多数名称之间使用逗号,而 and 仅用于最后一个。那将是:

    select t1.*, t2.profnames
    from table1 t1 join
         (select t2.courseid,
                 (group_concat(case when seqnum > 1 then profname end) || ', and '
                  max(case when seqnum = 1 then profname end)
                 ) as profnames
          from (select t2.*,
                       row_number() over (partition by courseid order by profname desc) as seqnum,
                from table2 t2
               ) t2
          group by t2.courseid
         ) t2
         on t1.courseid = t2.courseid;
    

    【讨论】:

      猜你喜欢
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      • 1970-01-01
      • 2020-11-09
      • 2020-07-24
      相关资源
      最近更新 更多