此查询将生成所需的 Pivot:
SELECT a.article, coalesce(i1.image,'') AS img1, coalesce(i2.image, '') AS img2
FROM (SELECT article FROM article_images GROUP BY article) a
LEFT JOIN article_images i1 ON a.article = i1.article AND i1.image =
(SELECT image FROM article_images WHERE article = a.article
ORDER BY image LIMIT 1)
LEFT JOIN article_images i2 ON a.article = i2.article AND i2.image =
(SELECT image FROM article_images WHERE article = a.article
ORDER BY image LIMIT 1 OFFSET 1);
有点复杂,但是这个子查询可以在 MySQL + PostgreSQL 中工作。
要更新使用(这UPDATE
是 MySQL 特定的):
UPDATE articles a, (SELECT a.article, coalesce(i1.image, '') AS img1,
coalesce(i2.image, '') AS img2
FROM (SELECT article FROM article_images GROUP BY article) a
LEFT JOIN article_images i1 ON a.article = i1.article AND i1.image =
(SELECT image FROM article_images WHERE article = a.article
ORDER BY image LIMIT 1)
LEFT JOIN article_images i2 ON a.article = i2.article AND i2.image =
(SELECT image FROM article_images WHERE article = a.article
ORDER BY image LIMIT 1 OFFSET 1)) AS s
SET a.image2 = s.img1, a.image3 = s.img2
WHERE a.article = s.article;
如果您的数据库支持窗口函数 + CTE,如 SQL Server、PostgreSQL 或 ORACLE,则可以使用以下查询来生成 Pivot:
WITH rowed AS (
SELECT article, image,
row_number() OVER (PARTITION BY article ORDER BY image) AS row
FROM article_images)
SELECT a.article, coalesce(i1.image, '') AS img1, coalesce(i2.image, '') AS img2
FROM (SELECT article FROM article_images GROUP BY article) AS a
LEFT JOIN rowed i1 ON i1.article = a.article AND i1.row = 1
LEFT JOIN rowed i2 ON i2.article = a.article AND i2.row = 2;
现在,每篇文章都有一个较短的行,您可以使用此子查询进行更新:
UPDATE articles a
SET image2 = s.img1,
image3 = s.img2
FROM (WITH rowed AS (
SELECT article, image,
row_number() OVER (PARTITION BY article ORDER BY image) AS row
FROM article_images)
SELECT a.article, coalesce(i1.image, '') AS img1, coalesce(i2.image, '') AS img2
FROM (SELECT article FROM article_images GROUP BY article) AS a
LEFT JOIN rowed i1 ON i1.article = a.article AND i1.ROW = 1
LEFT JOIN rowed i2 ON i2.article = a.article AND i2.ROW = 2) AS s
WHERE a.article = s.article;
此UPDATE
查询将在 PostgreSQL 中工作,但在 ORACLE / SQL Server 上可能不会。
您可以使用MySQL和PostgreSQL变体。