SQL表连接

时间:2016-10-07 14:23:27

标签: sql postgresql

我正在寻找一种方法来获取复杂连接的单个sql查询中的记录。我有三个表可以说用户,user_projects和约会。用户可以分配到多个项目,用户可以在不同的日期进行多次约会。如何选择分配给project1和project2并在date1和date2上进行约会的所有用户?我正在使用postgres 9.5

示例数据:

users表:

id, name    
1, Steve  
2, Bill  
3, Emma  

user_projects表:

id, user_id, project_id  
1, 1, 1  
2, 2, 1  
3, 3, 1  
4, 1, 2  

appointments表:

id, user_id, date  
1, 1, 2016-10-07  
2, 2, 2016-10-07  
3, 3, 2016-10-07  
4, 1, 2016-11-15  
5, 2, 2016-11-15  

对于这种特殊情况,我想说我想找到属于id为1和2的项目的所有用户,并在2016-10-07和2016-11-15的日期预约了。并且预期的输出是它应该只包括id为1的用户ie。史蒂夫在这种情况下

2 个答案:

答案 0 :(得分:1)

也许我在问题中遗漏了一些东西。看起来像是一个简单的加入我:

select distinct u.id
from users u
join user_projects up1 on u.id=up1.user_id
join user_projects up2 on u.id=up2.user_id
join appointments a1 on u.id=a1.user_id
join appointments a2 on u.id=a2.user_id
where up1.project_id = 1
and up2.project_id = 2
and a1.date = '2016-10-07'
and a2.date = '2016-11-15'

这是一个小提琴:http://sqlfiddle.com/#!15/415fd/1/0

答案 1 :(得分:0)

print "$myhash{'key1'}->[0]   and  $myhash{'key1'}->[1]\n";
print "$myhash{'key2'}->[0]   and  $myhash{'key2'}->[1]\n";
.......
print "$myhash{'key100'}->[0]   and  $myhash{'key100'}->[1]\n";

另一种方法应该具有相同的性能(也许这看起来更好,因为线路较少?):

SELECT ID
FROM USERS U
JOIN (
  -- Users in two projects
  SELECT USER_ID 
  FROM USER_PROJECT
  WHERE PROJECT_ID = 1

  INTERSECTION

  SELECT USER_ID 
  FROM USER_PROJECT
  WHERE PROJECT_ID = 2
) UP ON U.ID = UP.USER_ID
JOIN (
  -- user ids that have appointments on two dates:
  SELECT USER_ID
  FROM APPOINTMENT 
  WHERE DATE = '2016-10-07'

  INTERSECTION

  SELECT USER_ID
  FROM APPOINTMENT 
  WHERE DATE = '2016-11-15'
) A ON U.ID = A.USER_ID