我必须使用名为booksauthors的表格。
这是我的books表:
php - MySQL:如何根据另一个表的可用性进行选择-LMLPHP
它包含书名、作者姓名和对这本书的描述。
这是我的authors表:
php - MySQL:如何根据另一个表的可用性进行选择-LMLPHP
它包含作者姓名、作者居住的城市和作者肖像(描述)。
我的问题是:我如何才能将作者所在城市的SELECT *行设置为books表中的Berlin行。
在这种情况下,当city=Berlin时,应该选择authorstitle = "Something title AAA"的行。
这就是我尝试过的:

$stmt = $pdo->prepare('SELECT title, author, description FROM books JOIN authors ON :city = city');

$stmt->execute(array(':city' => "Berlin"));

但没用。我没有输出。我做错什么了?

最佳答案

您需要以下查询的结果:

SELECT books.* FROM books INNER JOIN authors ON books.author = authors.name
WHERE authors.city = 'Berlin'

对于PHP/PDO,它看起来如下所示:
$stmt = $pdo->prepare('SELECT books.* FROM books INNER JOIN authors ON books.author = authors.name WHERE authors.city = :city');
$stmt->execute(array(':city' => "Berlin"));

查询的ON部分定义表booksauthors之间的关系。在这个连接之后,您可以将两个表想象为一个包含所有列的大表。在查询的WHERE部分,定义过滤器以获取作者来自指定books的所有:city(在您的示例柏林)。

10-05 20:28
查看更多