开发者

SQL Concat Query

I have two tables like this:

TABLE user(
id     CHAR(100)
text   TEXT
)

TABLE post(
postid     CHAR(100)
postedby   CHAR(100)
text       TEXT
FOREIGN KEY (postedby) references user
);

I need a query that for each user concatenates the TEXT colum开发者_如何学JAVAn of all posts of that user and put them in the text column of the user. the order is not important. What should I do?


To select the values use GROUP_CONCAT:

SELECT postedby, GROUP_CONCAT(text)
FROM post
GROUP BY postedby

To update your original table you will need to join this result with your original table using a multi-table update.

UPDATE user
LEFT JOIN
(
    SELECT postedby, GROUP_CONCAT(text) AS text
    FROM post
    GROUP BY postedby
) T1
ON user.id = T1.postedby
SET user.text = IFNULL(T1.text, '');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜