我正在编写一个与 MySQL 数据库交互的应用程序。
我有 3 个表,“类别”、“书籍”和“book_category”。
/* stores properties for categories */
`categories` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(140) NOT NULL UNIQUE,
PRIMARY KEY (`id`)
);
/* stores properties for books */
`books` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` int(11) NOT NULL,
`read` tinyint(1) NOT NULL default 0,
`creation_date` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);
/* matches books against categories */
`book_category` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`category_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
);
我有 2 个变量来执行搜索。
<?php
$categoryString = 'python'; // books saved under python
$readBool = 1; // all books that have been read
?>
我想编写以下 SQL 查询:
选择所有已读过的Python书籍(即book.read = 1)。
我的SQL知识非常有限,请帮忙。
最佳答案
这应该可以解决问题:
SELECT books.id, books.title, books.`read`, categories.name
FROM books
INNER JOIN book_category ON books.id = book_category.item_id
INNER JOIN categories ON book_category.category_id = categories.id
WHERE books.read = 1
AND categories.name = 'python'
这是一个 SQL fiddle来演示。
关于php - 多表SQL搜索查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15898914/