1

Folks

I have a table as below

enter image description here

We are suppose to add a new column i.e parent_country after countryname column and result should be as below

id parentid  countryname                Parent_country

39  0        Barbados                     Barbados
40  39       Barbados mobile              Barbados
41  39       Mobile Digicel               Barbados
42  0        Anguilla                     Anguilla 
43  42       Anguilla Mobile              Anguilla 
44  42       hello Mobile Digicel         Anguilla 

Thanks

4

3 回答 3

4

我认为您不应该添加一列。您正在打破规范化的基本规则之一。这是一个查询,可为您提供所需的结果。

SELECT tbl.id as id
  , tbl.parentid as parentid
  , tbl.countryname as countryname
  , COALESCE(parent.countryname, tbl.countryname) as Parent_country
FROM tbl
LEFT JOIN tbl AS parent
ON tbl.parentid = parent.id

并且它更容易变成一个视图,该视图(虽然不可更新)可以模仿一个表以用于读取目的

CREATE VIEW tbl_trick_business_team AS
SELECT tbl.id as id
  , tbl.parentid as parentid
  , tbl.countryname as countryname
  , COALESCE(parent.countryname, tbl.countryname) as Parent_country
FROM tbl
LEFT JOIN tbl AS parent
ON tbl.parentid = parent.id
于 2013-10-09T11:18:09.357 回答
1

不会添加列,因为数据可以通过自拍连接获得,并且会破坏规范化 - 您将在数据库中使用更多空间。然而,在某些情况下,它可能对速度有益。

但如果你必须,我们去

ALTER TABLE tablename ADD COLUMN p_name(text);


UPDATE tablename
INNER JOIN
  (SELECT id,
          parentid,
          country_name
   FROM tablename)a ON tablename.parent_id=a.id
SET tablename.p_name=a.country_name;
于 2013-10-09T11:30:04.983 回答
0

您需要将 id 传递给$id变量,然后编写查询

UPDATE tablename SET Parent_country='Barbados' WHERE id='".$id."' LIMIT 1"
于 2013-10-09T11:11:09.963 回答