2

我有 2 个表,一个包含大量数据行,另一个包含用户迄今为止使用的行。如何使用单个查询允许我从主表中提取 3 个项目,但只能提取给定用户以前未见过的行。

示例表是:

CREATE TABLE `main_index` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

insert into `main_index` set `id`='1', `name`='something1';
insert into `main_index` set `id`='2', `name`='something2';
insert into `main_index` set `id`='3', `name`='something3';
insert into `main_index` set `id`='4', `name`='something4';
insert into `main_index` set `id`='5', `name`='something5';

CREATE TABLE `seen_index` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(12),
  `row_id` int(12),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

insert into `seen_index` set `user_id`='1', `row_id`='3';
insert into `seen_index` set `user_id`='1', `row_id`='5';
insert into `seen_index` set `user_id`='2', `row_id`='1';
insert into `seen_index` set `user_id`='2', `row_id`='3';
insert into `seen_index` set `user_id`='2', `row_id`='4';

为此,使用 user_id 为“1”,查询应返回:1、2、4

4

1 回答 1

4

此查询将起作用:

SELECT
*
FROM
main_index
WHERE
id NOT IN (
    SELECT row_id FROM seen_index WHERE user_id = 1
)

这是小提琴

另一种方法是:

SELECT
*
FROM
main_index
WHERE
NOT EXISTS (
    SELECT 1 FROM seen_index WHERE user_id = 1 AND row_id = main_index.id
)

这是小提琴

于 2013-05-15T22:22:34.450 回答