我有两个表Mention和Retweet
提
ID USER_SCREEN_NAME USER_ID MENTIONED_USER_ID MENTIONED_USER_NAME
15 user1 1 9 user 9
16 user 1 1 60 user 6
18 user 3 3 60 user 6
17 user 4 4 60 user 6
转推
ID USER_ID USER_SCREEN_NAME RETWEETED_STATUS_ID RETWEETED_USER_STATUS_ID RETWEETED_USER_NAME
19 3 user 3 400 40 user 4
11 1 user 1 38 60 user 6
15 2 user 2 500 50 user 5
13 4 user 4 38 60 user 6
我想要的是一个单独的表,其中包含用户提到或转发的信息,或者两者都包含在表中,因此输出应该是这样的(User_id(M)被提到用户ID和User_ID(R)被转发的用户ID)
USER_ID (M) USER_ID (R) USER_S_NAME MENTIONED_USER RETWEETED_USER
1 1 user 1 user 6 user 6
1 1 user 1 user 9 Null
3 3 user 3 user 6 Null
3 3 user 3 Null user 4
4 4 user 4 user 6 user 6
Null 2 user 2 Null user 5
但是我得到了这个结果
USER_ID (M) USER_ID (R) USER_S_NAME MENTIONED_USER RETWEETED_USER
1 1 user 1 user 6 user 6
1 1 user 1 user 9 Null
3 3 user 3 user 6 Null
4 4 user 4 user 6 user 6
Null 2 Null Null Null
它适用于提及表,但不适用于转发表 这是我的查询
SELECT
MT.USER_ID AS USER_ID,
r.USER_ID AS USER__ID,
mt.USER_SCREEN_NAME AS USER_S_NAME,
mt.MENTIONED_USER_NAME AS MENTIONED_USER,
(
SELECT
RETWEET.RETWEETED_USER_NAME
FROM
RETWEET
WHERE
RETWEETED_USER_STATUS_ID = mt.MENTIONED_USER_ID
AND ROWNUM = 1
AND USER_ID = MT.USER_ID
) AS RETWEETED_USER
FROM
MENTIONS mt
FULL OUTER JOIN RETWEET r ON MT.USER_ID = r.USER_ID --where MT.M_USER_ID=r.O_USER_ID
GROUP BY
MT.USER_ID,
mt.USER_SCREEN_NAME,
r.USER_ID,
mt.MENTIONED_USER_NAME,
MT.MENTIONED_USER_ID,
r.RETWEETED_USER_STATUS_ID
ORDER BY
mt.USER_ID
答案 0 :(得分:0)
只需添加JOIN
子句即可提及/转发ID字段。不需要GROUP BY
并且不清楚为什么需要子查询。但是,使用FULL OUTER JOIN
无法获得完整的所需结果,因为 nulls 将出现在相应的不匹配的左表或右表中:
SELECT
mt.USER_ID AS "USER_ID (M)",
r.USER_ID AS "USER__ID (R)",
mt.USER_SCREEN_NAME AS "USER_S_NAME",
mt.MENTIONED_USER_NAME AS "MENTIONED_USER",
r.RETWEETED_USER_NAME AS "RETWEETED_USER"
FROM
MENTION mt
FULL OUTER JOIN RETWEET r ON mt.USER_ID = r.USER_ID
AND mt.MENTIONED_USER_ID = r.RETWEETED_USER_STATUS_ID
ORDER BY mt.user_id, r.user_id
-- USER_ID (M) USER__ID (R) USER_S_NAME MENTIONED_USER RETWEETED_USER
-- 1 1 user 1 user 6 user 6
-- 1 (null) user1 user 9 (null)
-- 3 (null) user 3 user 6 (null)
-- 4 4 user 4 user 6 user 6
-- (null) 2 (null) (null) user 5
-- (null) 3 (null) (null) user 4
请参阅使用 PostgresSQL 9.3 作为方言的SQL Fiddle,因为已知Oracle不会在小提琴中工作。