在下面的数据库中,我需要所有用户及其位置,没有重复,并且首先列出了新泽西州的用户。
(如果他们有新泽西地址,我不需要他们的其他地址。为清楚起见,简化了数据库)。
> 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 |
以下是我的一些尝试及其输出。从我读到的[我在这上面花了几个小时],我认为这被称为模棱两可的 GROUP BY 查询,只有 MySQL 才允许。
不过,我想不出正确的方法来做到这一点。请帮忙!
期望的结果:
| user | state |
|--------|---------|
| 02 | NJ |
| 03 | NJ |
| 01 | NY |
其他尝试:
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 |