0

I have two tables t1 and t2 with the same structure

id INT
userid INT
date DATETIME

The first table contains my data, while the second table is kind of helper table which contains rows for 10 fix dates and userid = -1 What i need is a SELECT which gives me all rows from t1 with userid=X joined(merged) with all rows from t2 which date is not already in the result of t1.

Pseudo code

SELECT id, date
FROM t1, t2
WHERE (t1.userid=:id OR t2.userid=-1) AND t2.date NOT IN t1.date

Sample:

t1:

id    userid     date
1     1          2015-12-01
2     1          2015-12-02
3     1          2015-12-03
4     2          2015-12-01
5     2          2015-12-02

t2:

id    userid    date
1     -1        2015-12-01
2     -1        2015-12-02
3     -1        2015-12-03
4     -1        2015-12-04
5     -1        2015-12-05

Expected output for userid=1:

1      1        2015-12-01
2      1        2015-12-02
3      1        2015-12-03
4     -1        2015-12-04
5     -1        2015-12-05

Thanks for your help

Thallius
  • 2,482
  • 2
  • 18
  • 36

1 Answers1

1

I'll use a union select for doing this.

SELECT 
id, date
FROM 
t1
WHERE 
t1.id=:id
UNION ALL
(SELECT 
id, date
FROM 
t2
WHERE
t2.id=-1
AND t2.date NOT IN (SELECT date FROM t1 WHERE t1.userid=:id))
phsaires
  • 2,188
  • 1
  • 14
  • 11