如何根据特定条件查询多个MySQL表?

时间:2013-05-15 22:16:50

标签: mysql sql

我有两个表,一个包含大量数据行,另一个包含用户使用过的日期行。如何使用单个查询,允许我从主表中提取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

1 个答案:

答案 0 :(得分:4)

此查询将起作用:

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

这是fiddle

另一种方法是:

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

这是fiddle