0

我有两个名为 Workers 和 Stats 的表

在 Workers 表中,有一个很大的名字和姓氏列表(愚蠢地)放在一列中,其结构类似于:

NameID,   Name
  1,      John
  2,      Smith
  3,      McDonald
  4,      Harry

在 Stats 表中是工人的所有统计信息,如下所示:

id, firstnameid, secondnameid,  wage,    sold
 1,    4,           3,          1000,    10
 2,    1,           2,          2000,    20

因为这太不方便了,所以我正在尝试编写一个查询或将 Stats 表 nameids 更改为实际名称的东西,例如:

UPDATE `Stats` SET `Stats.firstnameid` =  `Workers.Names` 
WHERE `Stats.firstnameid` = `Workers.NameID`

然后对 secondnameid 执行相同的操作

因此,如果这可行,结果将是 Stats 表将更改为如下所示(使用我上面显示的示例表):

 id,  firstnameid, secondnameid,       wage,    sold
 1,    Harry,      McDonald,          1000,     10
 2,    John,       Smith,             2000,    20

有谁可以帮我离开这里吗?

谢谢。

4

2 回答 2

1

不要这样做!

而是创建一个视图:

create view v_stats as
    select s.id, fname.name as firstname, lname.name as lastname, s.wage, s.sold
    from stats s left outer join
         workers fname
         on s.firstnameid = fname.nameid left outer join
         workers lname
         on s.lastnameid = lname.nameid;

I have no idea why someone would design a database, splitting up the names like that. Ok, that seems like bad database design or whatever. You don't make it any better by compounding the problem by copying the names over. Presumably, that table is maintained somehow.

If two employees have the same first name, do they have one row or two in the workers table?

于 2013-03-30T12:50:15.520 回答
1

First, you will need to change your table structure. As for as moving the data, something like the below.

UPDATE
    Stats
SET
    s.firstName = w1.name,
    s.secondName= w2.name
FROM Stats AS s
INNER JOIN Workers AS w1 ON s.firstnameid = w1.NameID
INNER JOIN Workers AS w2 ON s.secondnameid= w2.NameID

I do like the idea of a workers table, but your workers table is really a name table which is very strange. I would want a workers table which had columns firstname, lastname, address, etc.

于 2013-03-30T12:56:22.143 回答