gpt4 book ai didi

mysql - 将 LEFT JOIN 与子查询组合时的 SQL DISTINCT

转载 作者:行者123 更新时间:2023-11-29 06:17:04 27 4
gpt4 key购买 nike

我有以下两个 SQL 表用于存储电影标题以及我观看它们的日期:

CREATE TABLE movies (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
title varchar(90) NOT NULL,
year varchar(7) DEFAULT NULL,
watchAgain enum('0', '1') NOT NULL DEFAULT '0',
PRIMARY KEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

INSERT INTO movies (id, title, year, watchAgain)
VALUES (1, 'Wall Street', '1987', '1'), (2, 'Wag the Dog', '1997', '1');

CREATE TABLE movies_seen (
object_id int(10) NOT NULL DEFAULT '0',
date varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci
NOT NULL DEFAULT '0',
seen_again enum('0', '1') NOT NULL DEFAULT '0',
PRIMARY KEY (object_id, date)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `movies_seen` (object_id, date, seen_again)
VALUES (1, '1156187700', '0'), (1, '1218395700', '0'), (2, '0', '0');

要查找我应该再次观看的电影,我会向数据库询问带有 seen_again == 1 的标题,或者如果 seen_again == 0 并且它未存储在 movies_seen:

SELECT m.year, m.title, s.date AS last_seen
FROM movies m
LEFT JOIN movies_seen s ON m.id = s.object_id
WHERE
(
m.watchAgain = '0'
AND m.id NOT IN (SELECT s.object_id
FROM movies m
INNER JOIN movies_seen s ON m.id = s.object_id)
OR m.watchAgain = '1'
)
ORDER BY m.title

这基本上有效,但是当 movie_seen 表具有同一标题的 2 个完整内容时,它会在结果中显示重复:

year    title           last_seen 
1997 Wag the Dog 0
1987 Wall Street 1156187700
1987 Wall Street 1218395700

如果我只获取标题,它可以与 DISTINCT 一起使用,但由于我需要额外的列,这显然会失败。有想法吗?

最佳答案

在 MySQL 中,GROUP BY 子句可以执行与 DISTINCT 相同的任务

SELECT m.year
, m.title
, s.date AS last_seen
FROM movies m
LEFT JOIN movies_seen s ON m.id = s.object_id
WHERE (m.watchAgain = '0'
AND m.id NOT IN (SELECT s.object_id
FROM movies m
INNER JOIN movies_seen s ON m.id = s.object_id)
OR m.watchAgain = '1')
GROUP BY m.title /*<<--- this will do a distinct on title only*/
ORDER BY m.title

据我所知,这只适用于 MySQL。

顺便说一句:由于您在 m.title 上进行分组,MySQL 对标题进行了排序,因此技术上不再需要 ORDER BY 子句。

关于mysql - 将 LEFT JOIN 与子查询组合时的 SQL DISTINCT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5819506/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com