F
F
furyon2016-03-31 21:08:58
PostgreSQL
furyon, 2016-03-31 21:08:58

How to make a query in JOIN?

Hello!
I use PostgreSQL. There is a request, it has a lot of conditions to change it too lazily, you need to add a condition, I wanted to add join neatly, here is the simplest example:

CREATE TABLE t1 (
  id int
);
INSERT INTO t1 (id) VALUES (1);
INSERT INTO t1 (id) VALUES (2);
INSERT INTO t1 (id) VALUES (3);

CREATE TABLE t2 (
  t1_id  INT,
  status INT
);
INSERT INTO t2 (t1_id, status) VALUES (1, 1);
INSERT INTO t2 (t1_id, status) VALUES (1, 1);
INSERT INTO t2 (t1_id, status) VALUES (1, 3);

I make a request:
SELECT t1.*
FROM t1
  INNER JOIN t2 ON (t1.id = t2.t1_id AND t2.status = 1)
WHERE
  id=1 OR id=2 OR id=3

In WHERE, just for example, there are a lot of conditions
. As a result, I will get 2 identical records with id = 1 , although I need only unique records in t1 (the data from t2 does not interest me, I just need the condition to match there). I can certainly solve the problem by adding a GROUP BY id to the end, but that doesn't smell good.
I smoked about different Joins, but nothing came of it.
I will be grateful for any help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2016-03-31
@furyon

You have 2 records in t2 that satisfy the condition, so there are 2 rows in the result.
To remove duplicate records, add distinct:
select distinct ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question