需要SQL来获取具有两个相应条目的记录

时间:2010-07-15 08:34:46

标签: sql mysql

我有一张表格,其中包含相应帐号的联系方式:

Contacts_Accounts Table

contact id | account ID
=======================
1          | 12
1          | 13
1          | 14
2          | 12
2          | 13
3          | 12

如何创建一个sql查询,返回所有具有BOTH帐号12和13的条目...例如我在这里使用MYSQL

3 个答案:

答案 0 :(得分:4)

这个嵌套查询应该可以解决问题:

SELECT * FROM Contacts_Accounts where account_ID = 12 and contact_id in (SELECT contact_id from Contacts_Accounts where account_ID = 13)

答案 1 :(得分:2)

SELECT 
  contact_id
FROM
  contacts_accounts
WHERE 
  account_id in (12,13)
GROUP BY 
  contact_id
HAVING count(account_id) = 2

答案 2 :(得分:0)

或者您可以使用group_concat,它将以逗号分隔列表返回account_id。

SELECT contact_id, group_concat(account_id) FROM contacts_accounts GROUP BY contact_id;

不确定这是否是您所追求的但是group_concat比我找到的嵌套查询更快,如果上述查询不符合您的要求,您可以解析更多的args到group_concat。