Need SQL to get a record with two matching records

I have a table that contains contact details for the corresponding account numbers:

Contacts_Accounts Table

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

how can I make a sql query that returns all records that have BOTH numbers 12 and 13, for example ... I use MYSQL here

+3
source share
3 answers

This sub-query should do the trick:

SELECT * FROM Contacts_Accounts where account_ID = 12 and contact_id in (SELECT contact_id from Contacts_Accounts where account_ID = 13)
+4
source
SELECT 
  contact_id
FROM
  contacts_accounts
WHERE 
  account_id in (12,13)
GROUP BY 
  contact_id
HAVING count(account_id) = 2
+2
source

group_concat, account_id , .

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

Not sure what you need, but group_concat is faster than the subqueries I found, and there are more arguments that you can parse for group_concat if the above request does not meet your requirements.

0
source

Source: https://habr.com/ru/post/1754770/


All Articles