In the following db, I need all users and their locations, without duplicates, and with those in NJ listed first.
(If they have a NJ address, I do not need their other addresses. Database simplified for clarity).
> table address,
| id | state | City |
|------|--------|----------|
| 01 | NY | Gotham |
| 02 | NY | Uye |
| 03 | NJ | Hoboken |
| 04 | NJ | Newark |
> table contact
| user | address |
|--------|-----------|
| 01 | 01 |
| 02 | 02 |
| 02 | 03 |
| 03 | 04 |
Below are some of my attempts and their outputs. From what I have read [I have spent hours on this], I think this is called a ambiguous GROUP BY query, and is only allowed by MySQL.
I can't figure out the correct way to do this, though. Please help!
DESIRED RESULT:
| user | state |
|--------|---------|
| 02 | NJ |
| 03 | NJ |
| 01 | NY |
OTHER ATTEMPTS:
SELECT user, state FROM contact, address WHERE id = address;
// Duplicate users, and addresses I do not need.
| user | state |
|--------|---------|
| 01 | NY |
| 02 | NY |
| 02 | NJ |
| 03 | NJ |
SELECT user, state FROM contact, address WHERE id = address GROUP BY user;
// NY address. I need the NJ address.
| user | state |
|--------|---------|
| 01 | NY |
| 02 | NY |
| 03 | NJ |
SELECT user, state FROM contact, address WHERE id = address GROUP BY user HAVING state = 'NJ';
//Worse, now I lose my NY users, and one of my NJ users doesn't even show
| user | state |
|--------|---------|
| 03 | NJ |