使用连接查询

时间:2015-08-13 11:03:52

标签: sql sql-server database

表:帖子

id       user_id     group_id    Text
1         1            1         AAA
2         2            2         BBB
3         2            2         CCC
4         3            2         DDD
5         2            3         EEE

表:UserMaster

user_id     username   
1           Raj 
2           Meet
3           Kishan

表:组

group_id     groupname
1            JAVA
2            PHP
3            SEO

表:JoinRequest

id      user_id     group_id    status
1        1           3          deactive
2        2           2          active
3        2           1          active
4        1           3          active

我的查询:

//Help me improve my query to get the desired result.
select  * FROM Post  
where status = active in JoinRequest table

和user_id =' 2'

预期结果:

id     username       Groupname     Text     
1      Raj             JAVA         AAA
2      Meet            PHP          BBB
3      Meet            PHP          CCC
4      Kishan          PHP          DDD

3 个答案:

答案 0 :(得分:2)

select p.id, u.username, g.groupname, p.text
from posts p
join userMaster u on u.user_id = p.user_id
join groups g on g.group_id = p.group_id
join joinRequest r on r.user_id = p.user_id 
                  and r.group_id = p.group_id
where r.status = 'active'

答案 1 :(得分:1)

Select p.id, um.username, g.Groupname, p.Text
From Post as p
JOIN UserMaster as um
  ON p.user_id = um.user_id
JOIN Groups as g
  ON p.group_id = g.group_id
JOIN JoinRequest as jr
  ON p.user_id = jr.user_id
  AND p.group_id = jr.group_id
WHERE jr.status = 'active'

答案 2 :(得分:-1)

你可以得到这样的结果。

SELECT P.id,
       U.username,
       G.Groupname,
       P.Text
FROM   Post P
       INNER JOIN UserMaster U
               ON U.user_id = P.user_id
       INNER JOIN Groups G
               ON G.group_id = P.group_id
       INNER JOIN JoinRequest JR
               ON P.user_id = JR.user_id
                  AND P.group_id = JR.group_id
WHERE  JR.status LIKE 'active';