我有以下两个用于存储电影标题的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
这基本上有效,但是当movies_seen表对同一个标题有2个entires时,它会在结果中显示重复:
year title last_seen
1997 Wag the Dog 0
1987 Wall Street 1156187700
1987 Wall Street 1218395700
如果我只获取标题,它适用于DISTINCT,但由于我需要额外的列,这显然会失败。想法?
答案 0 :(得分:4)
在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
AFAIK,这只适用于MySQL。
顺便说一句:由于你在m.title上进行分组,MySQL对标题进行了排序,因此技术上不再需要ORDER BY
子句。
答案 1 :(得分:-1)
SELECT m.year, m.title, s.date AS last_seen
FROM movies m
WHERE exists
(
select 1 from movies_seen s
where m.id = s.object_id
and ( 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