任何帮助将不胜感激!
我正在尝试获取有关单个作者的信息(例如表中具有第一个 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/