php - 多表SQL搜索查询

标签 php mysql sql

我正在编写一个与 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/

相关文章:

php - PDO MSSQL 空查询错误

java - Apache Ignite JDBC 和具有第 3 方持久性的后写缓存策略

mysql - INNER JOIN、LEFT JOIN、RIGHT JOIN 和 FULL JOIN 有什么区别?

javascript - 删除模式中的所有表-sequelize nodejs

php - 我想在类别中按日期从早期到当前排列我的记录

php - 如何使用 img 标签设置背景图像

PHP+mySQL 麻烦。提供的参数不是有效的 MySQL 结果资源

php - mysql 插入...选择

php - 使用不同的字符集搜索数据库

mysql - 在 MySQL 中转换日期