【问题标题】:SQL select between 3 tables3个表之间的SQL选择
【发布时间】:2009-09-03 15:08:41
【问题描述】:

我有 3 张桌子

1。书籍

身份证 标题 作者ID

2。 t作者

身份证 名称

3。 TBookAuthors

bookID 作者ID

一本书可以有几个作者,一个作者可以写几本书

所以我需要按名称搜索一本书并选择一条记录中的所有作者。

我试过这样,但结果是几条记录(多少作者)。这条记录的唯一区别是作者的名字。

select a.[ID], a.[title], c.[name] 
from tBooks a
    inner join tBookAuthors b
    on a.[ID] = b.bookID
    inner join tAuthors c
    on b.[authorID] = c.[ID]
where title like '%Blen%'

【问题讨论】:

  • 您使用哪种数据库引擎(MSSQL、MySql...)?
  • 我猜是 SQL Server,基于方括号。
  • MS Access 也使用方括号。

标签: sql select


【解决方案1】:

如果您发布您正在使用的 SQL DBMS,这将非常有帮助。

例如在 MySQL 中你可以使用 GROUP_CONCAT-

【讨论】:

    【解决方案2】:

    将您的内连接更改为外连接,您的书籍可能没有对应的 tBookAuthors 或 tAuthors 记录。

    由于您应用了 where 子句过滤器,您实际希望返回多少本书?运行此查询以找出:

    select count(*)
    from tBooks 
    where title like '%Blen%'
    

    【讨论】:

      【解决方案3】:

      您可以尝试使用左连接而不是内连接来连接 a 和 b。

      SELECT a.ID, a.title, c.name
      FROM tBooks a
          LEFT JOIN tBookAuthors b
          ON a.ID = b.bookID
          LEFT JOIN tAuthors c
          ON b.authorID = c.ID
      WHERE a.title LIKE '%Blen%'
      

      【讨论】:

        【解决方案4】:
        SELECT a.name, b.title FROM tBookAuthors x INNER JOIN tAuthors a ON a.id = x.AuthorID 
        INNER JOIN tBooks b ON x.BookID = b.id
        WHERE b.Title LIKE '%this book title%';
        

        您也不需要 tBooks 表中的 authorID 列。

        【讨论】:

          【解决方案5】:

          试试这个。

           SELECT a.ID, a.title, c.name
           FROM tBooks a
           LEFT JOIN tBookAuthors b ON a.ID = b.bookID
           left JOIN tAuthors c ON b.authorID = c.ID
           WHERE a.title LIKE '%Blen%'
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-07-22
            • 2010-12-21
            • 1970-01-01
            • 2017-09-18
            • 2011-08-04
            相关资源
            最近更新 更多