Reputation: 33
I have 2 tables:
Therefore a buyer has to be a visitor as well.
Here are the data that I have:
PURCHASE_TABLE
day user_id_purchase item_id_purchase Type
---------- ---------------- ---------------- --------
26/05/2016 AAA 47332 Purchase
19/05/2016 BBB 46523 Purchase
VISIT_TABLE
day user_id_visit Type
---------- ------------- -----
18/06/2016 AAA Visit
26/05/2016 AAA Visit
19/05/2016 BBB Visit
18/05/2016 CCC Visit
Here is what I would like to have: day
user_id
type
item_id
from both tables
With the results:
day user_id type item_id
---------- ------- -------- -------
18/06/2016 AAA Visit
26/05/2016 AAA Visit
19/05/2016 BBB Visit
18/05/2016 CCC Visit
26/05/2016 AAA Purchase 47332
19/05/2016 BBB Purchase 46523
Nevertheless I am unable to do it. The result that I got is a multiplication of the number of rows so far: I got 4 rows(visit)*2 rows (purchase) instead of 4 rows+2 rows. Indeed, I got each purchase and each click with the purchase…
Here is the query that I use:
SELECT
visits.user_id,
coalesce(visits.day_visit, purchases.day_purchase) AS day,
coalesce(visits.type, purchases.type) AS type,
purchases.item_id_purchase
FROM
(SELECT DISTINCT
day AS day_visit,
user_id AS user_id,
'Visit' AS type
FROM visit
WHERE DAY >= '2016-01-01') visits,
(SELECT DISTINCT
day AS day_purchase,
user_id_slow AS user_id,
item_id AS item_id_purchase,
'Purchase' AS type
FROM purchase
WHERE AND Day >= '2016-05-02') purchases
WHERE visits.user_id_display = purchases.user_id
more ore less similar to what I found here: How can I merge the columns from two tables into one output? I think that it doesn't work since I am using columns which are different between the 2 tables.
I tried with JOINs (both INNER AND LEFT) as well and it did not bring better results.
Do you have any idea on how I can get the result I wish?
Thanks,
JP
Upvotes: 1
Views: 261
Reputation: 10357
You want all the rows of both tables displayed, which you can do with UNION
and faking the missing column from the Visit
table.
SELECT day_date, user_id, type, NULL AS item_id
FROM Visit
UNION
SELECT day_date, user_id, type, item_id
FROM Purchase
ORDER BY type DESC, user_id ASC , day_date ASC
Which gives the result
day_date user_id type item_id
------------ ------- ---------- -------
"18-06-2016" "AAA" "Visit" "NULL"
"26-05-2016" "AAA" "Visit" "NULL"
"19-05-2016" "BBB" "Visit" "NULL"
"18-05-2016" "CCC" "Visit" "NULL"
"26-05-2016" "AAA" "Purchase" "47332"
"19-05-2016" "BBB" "Purchase" "46523"
Upvotes: 4