dongwu4834 2017-01-12 17:16
浏览 15
已采纳

如何使用链接表正确显示记录

I'm having trouble displaying database records in the manner I want using PHP and Mysql.

I have 3 tables, BOOKS, AUTHORS, BOOKS_AUTHORS.

The BOOKS table has the following columns, book_id, title, publish_date, thumbnail. The AUTHORS table has the following columns, author_id, first_name, last_name. The BOOKS_AUTHORS table has the following columns, books_authors_id, book_id (linked to book_id in the BOOKS table), and author_id (linked to author_id in the AUTHORS table).

Here's the SQL I'm using to display the results.

SELECT books.book_id, title, publish_date, thumbnail, authors.author_id, first_name, last_name, books_authors.book_id, books_authors.author_id
FROM books, authors, books_authors
WHERE books.book_id = books_authors.book_id 
AND authors.author_id = books_authors.author_id 
AND books.book_id = (INSERT NUMBER HERE)

Everything works fine unless a book has more than 1 author. Let's say a book has 2 authors. I will get back 2 records that have the same title, publish_date, and thumbnail but each will have a different authors' name. So now I have 2 duplicate titles, 2 duplicate publish_dates, and 2 duplicate titles. This isn't how I want to display the records. I want both author names to appear under 1 title, 1 publish_date, and 1 thumbnail.

  • 写回答

1条回答 默认 最新

  • dongmuzhan4705 2017-01-12 17:36
    关注

    Try grouping by the fields you don't want duplicated, then using GROUP_CONCAT on the author information to have each author listed in the same row:

    SELECT books.book_id, title, publish_date, thumbnail,
    GROUP_CONCAT(CONCAT(authors.author_id,' ', first_name,' ', last_name))
    FROM books, authors, books_authors
    WHERE books.book_id = books_authors.book_id 
    AND authors.author_id = books_authors.author_id 
    AND books.book_id = (INSERT NUMBER HERE)
    GROUP BY books.book_id, title, publish_date, thumbnail
    

    I would also use an inner join instead of listing your tables and then a where clause. This is typically easier to read. So the middle section would be:

    FROM books
    INNER JOIN books_authors ON books.book_id = books_authors.book_id 
    INNER JOIN authors ON authors.author_id = books_authors.author_id 
    WHERE books.book_id = (INSERT NUMBER HERE)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 python进程启动打包问题
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题