我在 Oracle 数据库(10g Express)中有两个表
- 产品
- 产品图片
一个产品可以有多个图像。因此,从 product
到 product_image
存在一对多关系,并且 product_image
表具有引用以下主键的外键: 产品
表。
我需要获取一个产品列表,在检索的结果集的每一行中仅包含一个图像名称,无论中的图像如何Product_image
表(即使某些产品没有图像)。
要从 product_image
表中检索的图像名称通常是对每组图像进行排序后 product_image
表中的第一个图像名称对于每个产品按升序排列。类似下面的内容。
prod_id prod_name prod_image
1 aaa aaa.jpg //The first image name in the product_image table after sorting images for prod_id in ascending order.
2 bbb bbb.jpg //Similar to the first case.
3 ccc - //No image(s) found in the product_image table
4 ddd - //Similar to the previous case.
这两个表的一般连接语句类似于以下内容。
SELECT p.prod_id, p.prod_name, pi.prod_image
FROM product p
INNER JOIN product_image pi
ON p.prod_id=pi.prod_id;
使用单个 SQL 语句可以实现这一点吗?
最佳答案
如果我正确理解你的问题,我认为以下查询会起作用。我没有测试过。
SELECT p.prod_id, p.prod_name, MIN(DBMS_LOB.substr(pi.prod_image, 1))
FROM product p LEFT JOIN product_image pi
ON p.prod_id=pi.prod_id
GROUP BY p.prod_id, p.prod_name
ORDER BY p.prod_name;
关于oracle - 从 Oracle 中的其他表中检索仅包含单个项目的行列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14461306/