2011年8月31日 星期三

insert into , update 另類寫法

參考
---
CREATE TABLE it0815a (
id INT NOT NULL PRIMARY KEY,
name VARCHAR(5) NOT NULL,
sumb INT
);

CREATE TABLE it0815b (
id INT NOT NULL,
valuex INT NOT NULL
);

INSERT INTO it0815a(id,name) VALUES
(1,'A'), (2, 'B'), (3, 'C');

INSERT INTO it0815b VALUES
(1,2),(1,3),(1,2),(2,4),(2,3),(3,1),(3,2),(3,3);
---------------------------
UPDATE it0815a a
LEFT JOIN (SELECT id, sum(valuex) as sumx
FROM it0815b
GROUP BY id) b
ON a.id = b.id
SET a.sumb = b.sumx;

select * from it0815a;
+----+------+------+
| id | name | sumb |
+----+------+------+
| 1 | A | 7 |
| 2 | B | 7 |
| 3 | C | 6 |
+----+------+------+

---
update join 上面是mysql寫法,要調整:
UPDATE BookmarkUrls
SET BookmarkUrls.BlogID = D.BlogID
FROM
dbo.BookmarkUrls INNER JOIN
(
-- 找出Detail Table 最先新增的那筆資料
SELECT LinkID,UrlID,BlogID FROM dbo.BookmarkLinks as i
WHERE LinkID IN
(
SELECT MIN(LinkID )
FROM BookmarkLinks AS i2
GROUP BY(UrlID)
)
) AS D
ON BookmarkUrls.UrlID = D.UrlID

參考

沒有留言:

張貼留言