0

I have a MySQL table with the following pattern:

| customer_id | store_id | status_id |
|-------------|----------|-----------|
| 12345 | 12 | 5 |
| 12345 | 8 | 3 |
| 12345 | 6 | 8 |
| 14567 | 5 | 3 |
| 14567 | 5 | 6 |
| 16543 | 3 | 4 |
| 19876 | 3 | 5 |
| 19876 | 6 | 8 |

Say, I want to retrieve all rows...

  • with identical customer IDs
  • which in turn have different store IDs
  • which all should have a status ID higher than 4

The correct output for the example table would therefore be:

| customer_id | store_id | status_id |
|-------------|----------|-----------|
| 19876 | 3 | 5 |
| 19876 | 6 | 8 |

Currently, I successfully wrote down a query to select all rows with an identical customer_id:

SELECT *
FROM table
WHERE customer_id IN (
 SELECT customer_id
 FROM table
 GROUP BY customer_id
 HAVING COUNT(*) > 1
)

This query would pick me all rows with customer_id = 12345 as well, but since one of the status_id of these rows is smaller than 4, I don't want this customer_id.

As an additional question, how would the final query look like when ported to Doctrine/Symfony?

asked Feb 15, 2017 at 13:04
4
  • I sense ... min(status_id) > 4 might help. Commented Feb 15, 2017 at 13:26
  • Where exactly would you put that statement in my query? Commented Feb 15, 2017 at 13:30
  • 1
    Where aggregation is done would be a good spot I presume. Commented Feb 15, 2017 at 13:32
  • 2
    so, something along the lines of having count(*) > 1 and min(status_id) > 4, I guess? Commented Feb 15, 2017 at 14:14

1 Answer 1

1
SELECT b.*
 FROM (
 SELECT customer_id
 FROM tbl
 WHERE COUNT(*) = COUNT(DISTINCT STORE_id) -- no dup store_ids
 GROUP BY customer_id -- per customer
 HAVING MIN(status_id) > 4 -- all status_id > 4
 ) AS a
 JOIN tbl AS b -- go back to get other columns
 USING(customer_id);
answered Feb 17, 2017 at 0:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.