2015-12-14 403 views
2

我有兩個表,如下所示。下面提到的兩個表中的Id列值都是自動遞增的。

+----+-----------+----------------+
集團| Id |GroupId |GroupName |
+----+-----------+----------------+
| 1 |10 |[email protected] |
| 2 |20 |[email protected] |
| 3 |30 |[email protected] |
| 4 |40 |[email protected] |
+----+-----------+----------------+通過使用另一個表值查詢連接列值來更新列值

客戶
+---+-----------------+------------+----------+---------------+
| Id |GroupAliasName |Domain |GroupId |CustomerName |
+---+-----------------+------------+----------+---------------+
| 1 |Grp1 |abc.com |null |Cust1 |
| 2 |Grp2 |abc.com |null |Cust2 |
| 3 |Grp3 |xyz.com |null |Cust3 |
| 4 |Grp4 |def.com |null |Cust4 |
+---+-----------------+------------+----------+---------------+

現在從客戶'GroupAliasName''Domain'當作爲'[email protected]'級聯相當於'GroupName'集團表。

客戶表使用連接的值,我需要從集團表拉'GroupId'和填充相同的客戶表的'GroupId'如下

客戶
+----+----------------+------------+----------+---------------+
| Id |GroupAliasName |Domain |GroupId |CustomerName |
+----+----------------+-----------+---------+-----------------+
| 1 |Grp1 |abc.com |10 |Cust1 |
| 2 |Grp2 |abc.com |20 |Cust2 |
| 3 |Grp3 |xyz.com |30 |Cust3 |
| 4 |Grp4 |def.com |40 |Cust4 |
+----+----------------+------------+----------+---------------+

查詢,我試過是如下

UPDATE Customer SET GroupId = (SELECT GroupId FROM Group G WHERE GroupName = (SELECT CONCAT(GroupAliasName, '@', Domain) AS GroupName FROM Customer WHERE Domain IS NOT NULL) AND G.GroupName = GroupName);

,但我得到的錯誤爲'Subquery returns more than 1 row'
請建議或提供您的輸入。

+1

完全一樣的錯誤說:你的子查詢一個返回數據的多行/記錄的情況下,其中只有一個記錄/行是允許的。找出哪一個,然後修改它只返回一個單一的記錄/行。另外,當你同時改變它時,你不能使用表格作爲數據源。如果你想更新'customer',那麼請考慮使用update的'join'支持。 –

回答

1

試試這個:

update customer as cust 
inner join `group` grp on concat(cust.groupaliasname, '@', cust.domain) = grp.groupname 
set cust.groupId = grp.groupId; 
+0

工作正常(y) – Murali

1

有出頭嘗試這樣

UPDATE Customer as c 
INNER JOIN Group as g on ( CONCAT(c.GroupAliasName, '@', c.Domain) = g.GroupName) 
SET c.GroupId = g.GroupId; 
相關問題