根据与组的关联来选择用户ID

时间:2013-11-11 23:11:35

标签: mysql sql

我有一个数据库,其中groups有许多users(1:N)。这两个表被设计为每个组都有一个唯一的ID,每个用户都有唯一的ID。但是现在我遇到了一个问题,我需要选择一个组的ID以及该组中用户的ID(这与他的真实数据库ID不同)。有没有办法在MySQL中选择这些子ID而不实际更改用户表结构?

我当前的表结构是什么样的:

-----------------
| GROUPS        |
=================
| ID PK AUTO_INC|
| NAME          |
| DESCRIPTION   |
| ...other      |
| non-related   |
| columns       |
-----------------

------------------
| USERS          |
==================
| ID PK AUTO_INC |
| NAME           |
| GROUP          |
| AGE            | 
|...other        |
| non-related    |
| columns        |
------------------

编辑:我想要的是:

GROUPS
----------------------------------
| ID  | Name | Description | ... |
==================================
| 1   |  A   | First one   | ... |
| 2   |  B   | Second one  | ... |
| 3   |  C   | Third one   | ... |
----------------------------------
USERS
--------------------------------------
| ID  | Name    | Group  | Age | ... |
======================================
| 1   |  John   |   1    | 35  | ... |
| 2   |  Adam   |   1    | 22  | ... |
| 3   |  Bob    |   2    | 18  | ... |
| 4   |  Jane   |   1    | 38  | ... |
| 5   |  Emma   |   2    | 56  | ... |
| 6   |  Aaron  |   3    | 26  | ... |
| 7   |  Alice  |   2    | 48  | ... |
--------------------------------------

And as a result I would like to get:
-----------------------------------
| GID | UID| Name    |  Age | ... |
===================================
| 1   | 1  |  John   |  35  | ... |
| 1   | 2  |  Adam   |  22  | ... |
| 1   | 3  |  Jane   |  38  | ... |
| 2   | 1  |  Bob    |  18  | ... |
| 2   | 2  |  Emma   |  56  | ... |
| 2   | 3  |  Alice  |  48  | ... |
| 3   | 1  |  Aaron  |  26  | ... |
-----------------------------------

我希望现在有意义。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

我知道如何做到这一点的唯一方法是使用变量

select
    t.id,
    t.name,
    t.group,
    t.rank as newid
from ( 
    select
        u.id,
        u.name,
        u.group,
        If(@group <> u.`Group`, @rownum := 1, @rownum := @rownum + 1) AS rank, 
        @group := u.`Group`
    from
        Users u 
            cross join (
            select
                @rownum := NULL,
                @group := 0
        ) as r 
    order by
        u.group,
        u.id
    ) as t
order by 
    t.group,
    t.id;

这种方法不能保证有效,但在实践中似乎可以。

<强> Example SQLFiddle