简体   繁体   English

php / sql连接具有多个字段的表

[英]php/sql joining tables with multiple fields

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. 文章标题(作者1,作者2,作者3),期刊名称,出版日期。

I've made two tables. 我做了两张桌子。 One contains paper_id, author_id, paper_name, journal_name, date. 其中一个包含paper_id,author_id,paper_name,journal_name,日期。 Second one contains author_id, author_firstname, author_lastname. 第二个包含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_id:1
author_firstname: john 作者的名字:约翰
author_lastname: smith 作者的姓氏:史密斯

author_id: 1 author_id:1
author_firstname: bob author_firstname:鲍勃
author_lastname: thomas author_lastname:托马斯

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 我已经尝试加入author_id,但是它输出两次相同的论文(因为我有两位ID为1的作者。我需要有关如何更改表或以不同的方式加入表的建议,没有其他建议。感谢您的帮助。我也是初学者

不知道我是否收到您的问题,但是您有两个表,您的查询将类似于SELECT table1.id,列名FROM table1 INNER JOIN table2 ON table1.id = table2.id

I beleieve the correct strategy is to use GROUP_CONCAT on each paper to obtain a comma separated list of authors. 我相信正确的策略是在每篇论文上使用GROUP_CONCAT以获得逗号分隔的作者列表。 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 . 作为一个说明,每个组在下面具有一定的查询paper_id 将有相同的价值观paper_namejournal_namedate I include the columns other than paper_id so that they will be available in the SELECT clause. 我包括paper_id以外的列,以便它们在SELECT子句中可用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM