0

我正在编写一个与 MySQL 数据库交互的应用程序。

我有 3 张桌子,“类别”、“书籍”和“书籍类别”。

/* 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知识很有限,请大家帮忙。

4

7 回答 7

1

这应该可以解决问题:

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 小提琴。

于 2013-04-09T10:06:06.020 回答
0

试试这个-

select * from book_category
   LEFT JOIN books ON book_category.item_id = books.id
   LEFT JOIN category ON category.id = book_category.category_id
  WHERE category.name = 'python' AND
        book.read = 1
于 2013-04-09T10:06:24.037 回答
0
select b.title 
from books b
left join book_category bc on (b.id=bc.item_d) 
left join categories c on (c.id=bc.category_id) 
where b.read=1 and c.name='python'
于 2013-04-09T10:07:40.740 回答
0
SELECT * FROM books WHERE id IN (
    SELECT item_id FROM book_category WHERE category_id IN (
        SELECT id FROM category WHERE name = 'Python'
    )
)
于 2013-04-09T10:07:55.743 回答
0
SELECT *
FROM books AS b
  INNER JOIN book_category AS bc
    ON bc.item_id = b.id
  INNER JOIN categories AS c
    ON c.id = bc.category_id
WHERE b.read = 1 AND c.name='python'
于 2013-04-09T10:08:07.567 回答
0
SELECT b.title 
FROM books b, categories c, book_category bc
WHERE b.id = bc.item_id
  AND c.id = bc.category_id
  AND b.read
  AND c.name = 'python'

为确保您的查询快速运行,请确保您具有以下索引:

 books(id)
 categories(id, name)
 book_category(item_id)
 book_category(caregory_id)
于 2013-04-09T10:11:05.013 回答
0

试试这个

"select b.title from category c INNER JOIN book_category bc on bc.category_id = c.id INNER JOIN book b on b.id = b.id where b.read = '1' and c.name = 'python'";
于 2013-04-09T10:11:22.317 回答