1

我很难弄清楚如何为我的查询创建正确的语法。

这就是我要拉的。我有 2 张桌子。

Table 1 : Fields  (user_id, name)
Table 2 : Fields  (user_id, type, are_code, phone_number).

表 1 每个 user_id 只能有 1 条记录。

1 | John Doe

表 2 每个 user_id 最多可以有 3 条记录:

1 | Home | 123 | 456.4567
1 | Work | 000 | 987.1467
1 | Mobi | 098 | 987.1756

我如何选择所有内容,以便我的表将导致 1 条记录被拉出,如下所示:

user_id | name | home# | work# | mobi#

我试过这个,它根据表 2 中的条目数量复制和加倍行。

SELECT a.user_id, 
       b.area_code, b.phone_number
FROM users a
INNER JOIN user_contact_phones b ON a.user_id = b.user_id

不幸的是,这返回了 3 行,这不好:(。

1 | John Doe | area | home# | 
1 | John Doe | area | work# |
1 | John Doe | area | mobi# |

任何帮助和/或指针将不胜感激。

4

3 回答 3

2

试试这个:

SELECT
  u.user_id,
  u.name,
  MAX(CASE WHEN p.type = 'Home' THEN phone_number END) HomeNumber,
  MAX(CASE WHEN p.type = 'Work' THEN phone_number END) WorkNumber,
  MAX(CASE WHEN p.type = 'Mobi' THEN phone_number END) MobiNumber
FROM phones p
JOIN users u ON p.user_id = u.user_id
GROUP BY u.user_id, u.name

输出:

| USER_ID |     NAME | HOMENUMBER | WORKNUMBER | MOBINUMBER |
|---------|----------|------------|------------|------------|
|       1 | John Doe |   456.4567 |   987.1467 |   987.1756 |

在这里拉小提琴。

另请注意,您可以删除u.nameif u.user_iddetermine u.name... 这很可能是这种情况,因为它似乎是主键。这会加快速度。

注意:这假设您不能为同一用户拥有多个相同的类型(就像在您的示例数据中一样,它只有一列用于家庭、工作和移动。

于 2013-10-23T18:09:54.933 回答
1

Use user_contact_phones.type to get exact what you want, like-

SELECT a.user_id, 
       b.area_code, b.phone_number
FROM users a
INNER JOIN user_contact_phones b ON a.user_id = b.user_id where b.type='Home'
于 2013-10-23T18:06:28.190 回答
0

Here's a solution that will work:

select u.user_id, u.name,
    thome.area_code as home_area_code, thome.phone_number as home_phone_number,
    twork.area_code as work_area_code, twork.phone_number as work_phone_number,
    tmobi.area_code as mobi_area_code, tmobi.phone_number as mobi_phone_number  
from table1 u
    left outer join table2 thome on u.user_id = thome.user_id and thome.type = 'Home'
    left outer join table2 twork on u.user_id = twork.user_id and twork.type = 'Work'
    left outer join table2 tmobi on u.user_id = tmobi.user_id and tmobi.type = 'Mobi'

Please note the use of left outer join instead of inner join in case the record for a particular type does not exist. You will get null values for those columns in your result set with left outer join. With inner join, you would not get a result for a user that did not have all three types. Good luck!

于 2013-10-23T18:07:29.260 回答