我正在尝试获取已阅读的书籍(和藏书-我链接到书籍ID)。我使用2个左联接。
请参见下面的示例。
我正在获得以下结果:
我想获取此列表,但仅获取在a_books_subcollection中读取的集合。在此结果中,它显示了所有集合的读取时间,并且输出仅为集合3。
a_books
a_books_subcollection
a_read
内容
CREATE TABLE `a_books_subcollection` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`label` varchar(35) DEFAULT NULL,
`book_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `a_books_subcollection` (`id`, `label`, `book_id`)
VALUES
(1,'Collection 1',3),
(2,'Collection 2',3),
(3,'Collection 3',3);
CREATE TABLE `a_read` (
`label` varchar(35) DEFAULT NULL,
`book_id` int(11) DEFAULT NULL,
`readtime` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `a_read` (`label`, `book_id`, `readtime`)
VALUES
('Story 1',1,'2020-09-09'),
('Collection 3',3,'2020-09-09');
CREATE TABLE `a_books` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`label` varchar(35) DEFAULT NULL,
`is_collection` int(11) DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `a_books` (`id`, `label`, `is_collection`)
VALUES
(1,'story 1',NULL),
(2,'story 2',NULL),
(3,'story 3',1);
我的查询
SELECT a_books.* ,a_read.readtime,a_read.label
FROM a_books
LEFT JOIN a_books_subcollection
ON a_books_subcollection.book_id=a_books.id
LEFT JOIN a_read
ON a_books.id=a_read.book_id
ORDER BY a_books.id
答案 0 :(得分:0)
SELECT b.id,
b.label book_label,
b.is_collection,
r.readtime,
COALESCE(bs.label, b.label) label
FROM a_books b
LEFT JOIN a_books_subcollection bs ON bs.book_id=b.id
LEFT JOIN a_read r ON r.book_id = b.id AND r.label IN (b.label, bs.label)
ORDER BY id, label
答案 1 :(得分:0)
SELECT a.*,c.readtime ,IF(a.is_collection=1,b.label,c.label)
FROM a_books a
LEFT JOIN a_books_subcollection b ON b.book_id=a.id
LEFT JOIN a_read c on c.book_id=a.id and (c.label=b.label or c.label=a.label)
ORDER BY a.id,b.label
也许这可以解决您的问题,但是您想要从表label
或a_books_subcollection
中获取的字段a_read
的结果确实是模棱两可的。我添加条件来获取标签,如果来自表is_collection
的数据a_books
是1
从表a_books_subcollection
获取标签,否则从表a_read
获取标签