S
S
Sserge2014-07-06 17:56:41
MySQL
Sserge, 2014-07-06 17:56:41

How to select data by multiple fields in join?

Hello! I can't figure out how to make a request. There is a table A and B.
A table
row_id,name.
Table B:
row_id,table_a_id,status_id
As you can see, the tables have many-to-one relationships. Actually, I stumbled on the fact that I need to select all records from table A that have status_id = 1 and status_id = 2.
If I do a regular join, I get all the records where there is status 2 or status 1, but not where both statuses are simultaneous.
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Morozov, 2014-07-06
@Sserge

en.wikipedia.org/wiki/Having_(SQL)

SELECT A.row_id, A.name FROM A
INNER JOIN B ON (B.table_a_id = A.row_id)
WHERE B.status_id = 1 OR B.status_id = 2
GROUP BY A.row_id, A.name
HAVING SUM(1) = 2

A
Alex Kheben, 2014-07-06
@zBit

I have not worked with MySQL for a long time, but here is how I see the solution:

SELECT a.row_id, a.name
FROM a JOIN b ON b.table_a_id=a.id
WHERE a.id IN (
  SELECT a.id FROM a JOIN b ON b.table_a_id=a.id AND b.status_id=1
  INTERSECT
  SELECT a.id FROM a JOIN b ON b.table_a_id=a.id AND b.status_id=2
)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question