sql—选择一个表中包含另一个表中具有特定id的两条记录的所有记录

mitkmikd  于 2021-07-29  发布在  Java
关注(0)|答案(3)|浏览(457)

我有两张1:m关系的表。需要选择哪些人员记录在id为1和2的操作表中同时包含这两个记录

  1. People
  2. +----+------+--------------+
  3. | id | name | phone_number |
  4. +----+------+--------------+
  5. | 1 | John | 111111111111 |
  6. +----+------+--------------+
  7. | 3 | Jane | 222222222222 |
  8. +----+------+--------------+
  9. | 4 | Jack | 333333333333 |
  10. +----+------+--------------+
  11. Action
  12. +----+------+------------+
  13. | id | PplId| ActionId |
  14. +----+------+------------+
  15. | 1 | 1 | 1 |
  16. +----+------+------------+
  17. | 2 | 1 | 2 |
  18. +----+------+------------+
  19. | 3 | 2 | 1 |
  20. +----+------+------------+
  21. | 4 | 4 | 2 |
  22. +----+------+------------+
  23. Output
  24. +----+------+--------------+----------
  25. |PplId| name | Phone |ActionId |
  26. +-----+------+-------------+----+-----
  27. | 1 | John | 111111111111| 1 |
  28. +-----+------+-------------+----+-----
  29. | 1 | John | 111111111111| 2 |
  30. +-----+------+-------------+----+-----

返回同时具有actionid 1和actionid 2的人员的记录(具有actions中的记录)。

798qvoo8

798qvoo81#

窗口函数是一种方法。假设一个人的动作不重复:

  1. select pa.*
  2. from (select p.*, a.action, count(*) over (partition by p.id) as num_actions
  3. from people p join
  4. action a
  5. on p.id = a.pplid
  6. where a.action in (1, 2)
  7. ) pa
  8. where num_actions = 2;

在我看来,获得两行的动作细节似乎是多余的-你已经知道的行动。如果你只想要人民,那么 exists 我想到:

  1. select p.*
  2. from people p
  3. where exists (select 1 from actions where a.pplid = p.id and a.action = 1) and
  4. exists (select 1 from actions where a.pplid = p.id and a.action = 2);

使用正确的索引( actions(pplid, action) ),我希望有两个 exists 比…快 group by .

展开查看全部
uinbv5nw

uinbv5nw2#

使用subquery和join尝试下面的查询

  1. select a.Pplid, name, phone, actionid from (
  2. select a.pplid as Pplid, name, phone_number as phone
  3. from People P
  4. join Action A on a.pplid= p.id
  5. group by a.pplid, name, phone_number
  6. having count(*)>1 )P
  7. join Action A on a.Pplid= p.Pplid
ckx4rj1h

ckx4rj1h3#

试试这个

  1. IF OBJECT_ID('tempdb..#People') IS NOT NULL DROP TABLE #People
  2. CREATE TABLE #People (id INT, name VARCHAR(255), phone_number VARCHAR(50))
  3. INSERT #People
  4. SELECT 1, 'John', '111111111111' UNION ALL
  5. SELECT 3, 'Jane', '222222222222' UNION ALL
  6. SELECT 4, 'Jack', '333333333333'
  7. IF OBJECT_ID('tempdb..#Action') IS NOT NULL DROP TABLE #Action
  8. CREATE TABLE #Action (id INT, PplId INT, ActionId INT)
  9. INSERT #Action
  10. SELECT 1, 1, 1 UNION ALL
  11. SELECT 2, 1, 2 UNION ALL
  12. SELECT 3, 2, 1 UNION ALL
  13. SELECT 4, 4, 2
  14. GO
  15. SELECT p.ID AS PplId
  16. , p.name
  17. , p.phone_number AS Phone
  18. , a.ActionId
  19. FROM #People p
  20. JOIN #Action a
  21. ON p.ID = a.PplId
  22. WHERE p.ID IN ( SELECT PplId
  23. FROM #Action
  24. WHERE ActionId IN (1, 2)
  25. GROUP BY PplId
  26. HAVING COUNT(*) = 2 )
  27. AND a.ActionId IN (1, 2)
  28. GO
展开查看全部

相关问题