donglang6656 2015-06-25 01:01
浏览 33
已采纳

php / sql连接多个字段的表

I'm trying to echo info from a database onto the webpage. The page is supposed to have a bunch of article publications which includes the title, authors, journal name (if applicable), date published. For example:

  1. title of the article (with author 1, author 2, author 3), name of the journal, date published.

I've made two tables. One contains paper_id, author_id, paper_name, journal_name, date. Second one contains author_id, author_firstname, author_lastname.

The part I'm struggling with is outputting multiple authors. in the second table I have the following for first paper

author_id: 1
author_firstname: john
author_lastname: smith

author_id: 1
author_firstname: bob
author_lastname: thomas

I want to print this: Name of the paper (with john smith, bob thomas), journal name, date published.

I've tried joining author_id but it outputs the same paper twice (since i have two authors with id 1. I need suggestions as to how i should change the table or join it differently and what not. Any help will be appreciated, thanks. I'm also a beginner programmer

  • 写回答

2条回答 默认 最新

  • duandu1915 2015-06-25 01:18
    关注

    I beleieve the correct strategy is to use GROUP_CONCAT on each paper to obtain a comma separated list of authors. As a note, each group in the query below having a given paper_id will also have the same values for paper_name, journal_name and date. I include the columns other than paper_id so that they will be available in the SELECT clause.

    SELECT t1.paper_name,
        GROUP_CONCAT(CONCAT(t2.author_lastname, ', ', t2.author_firstname)
        SEPARATOR ' '),
        t1.journal_name, t1.date
    FROM table1 t1 INNER JOIN table2 t2
    ON t1.author_id = t2.author_id
    GROUP BY t1.paper_id, t1.paper_name, t1.journal_name, t1.date
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程