dougupang0901 2013-04-09 09:59
浏览 22
已采纳

多表SQL搜索查询

I am writing an app that interacts with a MySQL database.

I have 3 tables, 'categories', 'books' and '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`)
);

I have 2 variables to perform the search.

<?php
    $categoryString = 'python';  // books saved under python
    $readBool = 1;  // all books that have been read
?>

I would like to write the following SQL query:

Select all python books that have been read(i.e, book.read = 1).

My SQL knowledge is very limited, please help.

  • 写回答

7条回答 默认 最新

  • douchen2025 2013-04-09 10:06
    关注

    This should do the trick:

    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'
    

    And here's an SQL fiddle to demonstrate.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看