多表SQL搜索查询

时间:2013-04-09 09:59:20

标签: 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知识非常有限,请帮助。

7 个答案:

答案 0 :(得分: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 fiddle来演示。

答案 1 :(得分: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

答案 2 :(得分: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'

答案 3 :(得分:0)

SELECT * FROM books WHERE id IN (
    SELECT item_id FROM book_category WHERE category_id IN (
        SELECT id FROM category WHERE name = 'Python'
    )
)

答案 4 :(得分: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'

答案 5 :(得分: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)

答案 6 :(得分: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'";