MySQL查询以获取用户未加入的所有社区

时间:2019-05-21 08:27:23

标签: mysql

我想获取用户尚未加入的所有社区(基于不同的zip)。

我有一个用户表和其他几个这样的表:

表名:社区

CREATE TABLE neighborhood(
    `neighborhood_id` INT(11) NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(255) NOT NULL,
    `description` TEXT DEFAULT NULL,
    `neighborhood_postal_code` VARCHAR(255) NOT NULL,
    `region_neighborhood` VARCHAR(255) NOT NULL,
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`neighborhood_id`),
    INDEX `neighborhood_region_neighborhood_FI_1` (`region_neighborhood`)
) ENGINE = InnoDB;

表名:user_neighborhood

CREATE TABLE user_neighborhood(
    `user_id` INT(11) NOT NULL,
    `neighborhood_id` INT(11) NOT NULL,
    `activity_circle` INT(1) DEFAULT 0,
    `duo_circle` INT(1) DEFAULT 0,
    FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`),
    FOREIGN KEY (`neighborhood_id`) REFERENCES `neighborhood` (`neighborhood_id`)
) ENGINE = InnoDB;

我尝试了以下查询,但结果不正确:

SELECT n.*
FROM `neighborhood` as n
left join user_neighborhood as un on n.neighborhood_id = un.neighborhood_id
where un.user_id != 1 and n.neighborhood_postal_code IN ('2000', '2100')

更新:我设法使用以下子查询使查询在第一次出现时看起来正确:

select *
from neighborhood
where neighborhood_id NOT IN (select neighborhood_id from user_neighborhood where user_id != 1)
AND neighborhood_postal_code IN ('2000', '2100')

但是,它也会返回(我)已经在的某些社区。对我来说,为什么只有一些是没有意义的。

1 个答案:

答案 0 :(得分:1)

为什么要在子查询中精确添加user_id!= 1?我认为,如果您知道要获取的用户ID,可以说user_id为10,则在子查询中使用其中user_id = 10,例如:

select *
from neighborhood
where neighborhood_id NOT IN (select distinct neighborhood_id from user_neighborhood where user_id = 10)
AND neighborhood_postal_code IN ('2000', '2100')

但是,如果要获取没有用户的所有邻居,则可以使用以下查询:

select *
from neighborhood
where neighborhood_id NOT IN (select distinct neighborhood_id from user_neighborhood)
AND neighborhood_postal_code IN ('2000', '2100')

希望这会有所帮助!