php - 使用 mySQL 表中的 JOIN 子句获取确切的作者和文章

标签 php mysql

任何帮助将不胜感激!

我正在尝试获取有关单个作者的信息(例如表中具有第一个 ID 的第一作者)并显示他的所有文章,仅此而已。

我正在尝试以下代码,使用 LEFT-JOIN 子句,并获取第一作者及其所有文章,但也获取其他作者和文章。

我是这个条款的新手,一些帮助会非常有用。

我应该更改条款还是?

$sql = <<<TAG
    SELECT authors.name as author_name,
           articles.title as article_title,
           articles.text as article_text,
           articles.author_id
    FROM authors
    LEFT JOIN articles
    ON authors.id = articles.author_id
TAG;


$result = mysqli_query($foo_connection, $sql);


if($result) {


    foreach($result as $key => $item_data){

        print $item_data['author_name']. " - " . $item_data['article_title'] . " - " . $item_data['article_text'] ."<br>";

    }

}
else {
    print "Something went wrong! ".mysqli_errno($sql);
}

最佳答案

您必须使用作者 ID 过滤结果。 如果您想动态选择作者 ID,则必须执行两个请求 - 第一个请求是您选择第一个作者(LIMIT 1),第二个请求是您选择该作者的所有文章。

您还可以在 where 子句中执行子查询,例如:

SELECT authors.name as author_name,
       articles.title as article_title,
       articles.text as article_text,
       articles.author_id
FROM authors
LEFT JOIN articles
ON authors.id = articles.author_id
WHERE authors.id IN (SELECT id FROM authors LIMIT 1)

此请求将仅选择表的第一作者(因为没有定义 where 子句,也没有顺序,基本上是第一个语句)。

编辑:

如果您已经从其他地方获得了作者 ID:

SELECT authors.name as author_name,
       articles.title as article_title,
       articles.text as article_text,
       articles.author_id
FROM authors
LEFT JOIN articles
ON authors.id = articles.author_id
WHERE authors.id = xxx

xxx 替换为您的作者 ID。

关于php - 使用 mySQL 表中的 JOIN 子句获取确切的作者和文章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49751999/

相关文章:

php - symfony2/ Twig : how to use include in a block used in a form theme?

mysql - MySQL新手,我得到了我想要的相反结果

mysql - 如何更改MySQL数据中的images/to asset/images?

php - 如何在串联值上选择最后插入的 ID

php - 使用 codeigniter 在 php URL 路由中发出警告

php - 与 OOP 概念斗争

mysql - SQL View 显示 12 个月和按年的间隔

mysql - 表中没有记录时无法获取地理点

PHP UTF 编码的 URL 字符串

javascript - PHP/html : instant search function: Can't search for foreign (e. g.Chinese)字符