このクエリは、目的のピボットを生成します。
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;
データベースがSQLServer、PostgreSQL、ORACLEなどのウィンドウ関数+ CTEをサポートしている場合は、代わりに次のクエリを使用してピボットを生成できます。
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;
これで、記事ごとに短い方法で1つの行ができ、このサブクエリを使用して以下を更新できます。
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 /SQLServerでは機能しない可能性があります。
MySQLとPostgreSQLの亜種をいじることができます。