“否定”SQL(postgres)查询

时间:2015-06-10 18:29:23

标签: node.js postgresql

我需要一些SQL查询的帮助。因为我是这个领域的新手,我无法真正解释谷歌我想做什么,我还没有找到任何正确的答案。我的桌子甚至可以吗?

我想收到所有的线程(id,name),这些线程不是我自己的线程,而且我已经没有投票了。 (即线程我可以投票)

数据库如下所示:

Threads
+----+-------------+---------+
| id | thread_name | user_id |
+----+-------------+---------+
|  1 | Soccer      |       1 |
|  2 | Running     |       1 |
|  3 | Swimming    |       2 |
+----+-------------+---------+

User
+----+--------+
| id |  name  |
+----+--------+
|  1 | Marcel |
|  2 | Marc   |
|  3 | Susy   |
+----+--------+

Votes
+----+-----------+---------+
| id | thread_id | user_id |
+----+-----------+---------+
|  1 |         1 |       3 |
|  2 |         1 |       2 |
|  3 |         2 |       3 |
+----+-----------+---------+

示例:

  • 如果用户1进行查询,他应该收到第3个帖子,因为它不是他自己的,他还没有投票。
  • 用户2应该收到第2个帖子
  • 用户4应该收到所有帖子

我试过了:

SELECT DISTINCT t.id, name FROM threads as t
LEFT JOIN votes as v ON v.thread_id = t.id
WHERE (v.user_id != USER_ID OR v.user_id IS NULL)
AND t.user_id != USER_ID 

我正在使用Sequelize(Node.js ORM)。 pgAdmin给了我以下(简化)作为模式 - 希望这有帮助:

-- Table: "threads"
-- DROP TABLE "threads";

CREATE TABLE "threads"
(
  id serial NOT NULL,
  name character varying(255),
  "createdAt" timestamp with time zone NOT NULL,
  "updatedAt" timestamp with time zone NOT NULL,
  "user_id" integer,
  CONSTRAINT "threads_pkey" PRIMARY KEY (id),
  CONSTRAINT "threads_user_id_fkey" FOREIGN KEY ("user_id")
      REFERENCES "users" (id) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE SET NULL
)
WITH (
  OIDS=FALSE
);
ALTER TABLE "threads"
  OWNER TO postgres;

-- Table: "votes"
-- DROP TABLE "votes";

CREATE TABLE "votes"
(
  id serial NOT NULL,
  "createdAt" timestamp with time zone NOT NULL,
  "updatedAt" timestamp with time zone NOT NULL,
  "user_id" integer,
  "thread_id" integer,
  CONSTRAINT "votes_pkey" PRIMARY KEY (id),
  CONSTRAINT "votes_thread_id_fkey" FOREIGN KEY ("thread_id")
      REFERENCES "threads" (id) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE SET NULL,
  CONSTRAINT "votes_user_id_fkey" FOREIGN KEY ("user_id")
      REFERENCES "users" (id) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE SET NULL
)
WITH (
  OIDS=FALSE
);
ALTER TABLE "votes"
  OWNER TO postgres;


-- Table: "users"
-- DROP TABLE "users";

CREATE TABLE "users"
(
  id serial NOT NULL,
  username character varying(255),
  "createdAt" timestamp with time zone NOT NULL,
  "updatedAt" timestamp with time zone NOT NULL,
   CONSTRAINT "users_pkey" PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
   ALTER TABLE "users"
      OWNER TO postgres;

谢谢。

1 个答案:

答案 0 :(得分:1)

这应该可以解决您的问题。

select t.id from threads as t where t.user_id != USER_ID and t.id not in 
(select v.thread_id from votes as v where v.user_id = USER_ID);