我必须使用名为books
和authors
的表格。
这是我的books
表:
它包含书名、作者姓名和对这本书的描述。
这是我的authors
表:
它包含作者姓名、作者居住的城市和作者肖像(描述)。
我的问题是:我如何才能将作者所在城市的SELECT *
行设置为books
表中的Berlin
行。
在这种情况下,当city=Berlin时,应该选择authors
和title = "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
部分定义表books
和authors
之间的关系。在这个连接之后,您可以将两个表想象为一个包含所有列的大表。在查询的WHERE
部分,定义过滤器以获取作者来自指定books
的所有:city
(在您的示例柏林)。