php - 带条件的 LEFT JOIN 未返回所需的数据

标签 php mysql join left-join

我想使用 MYSQL 进行左连接。目前我有一个类似这样的表:

CREATE TABLE `books` (
  `bookId` int(11) NOT NULL,
  `bookTitle` varchar(100) NOT NULL,
  `bookAuthor` varchar(100) NOT NULL,
  `bookStatus` tinyint(1) NOT NULL,
  `bookDeleteFlag` tinyint(1) NOT NULL
);  
CREATE TABLE `lends` (
  `lendId` int(11) NOT NULL,Primary
  `lendBookId` int(11) NOT NULL,
  `lendBorrowerName` Varchar(100) NOT NULL,
  `lendBorrowStatus` int(11) NOT NULL,
  `lendReturnStatus` int(11) NOT NULL,
  );

insert into books values (1, 'The Da Vinci Code', 'Dan Brown', 1,0)
insert into books values (2, 'Theory of Relativity', 'Albert Einstein', 1,0)
insert into books values (3, 'Harry Potter', 'J K Rowling', 1,0)

insert into books values (1, '1', 'Chris', 1,1)
insert into books values (2, '1', 'Lilly', 1,0)
insert into books values (3, '2', 'Chris', 1,0)
insert into books values (3, '3', 'Chris', 1,1)

想要的输出是这样的

bookId         bookTitle           availability
-----------------------------------------------
  1        The Da Vinci Code            0
  2        Theory of Relativity         0
  3        Harry Potter                 1

我基本上正在开发一个图书馆管理模块。我希望在图书搜索页面上列出该书的可用性。

我当前的代码是:

SELECT B.bookTitle,
       L.lendBorrowerName AS takenName,
       count(L.lendStatus) AS taken
FROM   books as B
LEFT JOIN lends AS L ON B.bookId = L.lendBookID
WHERE L.lendReturnStatus = 0 // if i remove this code, all rows in books table is listed. However i loose the ability to check the availability of that book
GROUP BY B.bookTitle

此问题的典型解决方案是什么? 提前致谢。

最佳答案

您需要将 where 子句中的条件移至 on 子句。当没有行匹配时,该列的值为 NULL 并且 WHERE 条件失败:

SELECT B.bookTitle,
       L.lendBorrowerName AS takenName,
       count(L.lendStatus) AS taken
FROM   books as B LEFT JOIN
       lends AS L
       ON B.bookId = L.lendBookID AND
          L.lendReturnStatus = 0
GROUP BY B.bookTitle;

关于php - 带条件的 LEFT JOIN 未返回所需的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30754526/

相关文章:

javascript - 如何存储不重置的测验的 JavaScript 计时器倒计时

sql - 使用 SQL 进行数据转换

mysql - Azure Testabo Cleardb 升级

mysql - SQL 关系、触发器和外键

mysql - 如何正确连接 MYSQL 中可能没有匹配结果的列?

mysql - 多个内部联接以获得复杂的报告,但不起作用

php使用join从数据库中选择数据

php - 我如何找出导致元素出现空格的原因? margin 和填充?

php - 处理我的 URL 请求的正确方法

PHP imagick 将图像从 CMYK 转换为 RGB 反转图像