[英]MYSQL Single query to retrieve both single row from one table and many rows as a single field from another
[英]MYSQL one to many relationship query returning a single row from 'many' table
我有2个mysql表,即“属性”和“图像”。
Properties
+------------+---------------+
| propertyId | propertyTitle |
+------------+---------------+
| 1 | 1 acre land |
| 2 | 2 acre land |
| 3 | 3 acre land |
+------------+---------------+
Images
+---------+---------------+---------------+
| imageId | image | propertyId |
+---------+---------------+---------------+
| 1 | land.jpeg | 1 |
| 2 | landview.jpg | 1 |
| 3 | viewland.jpeg | 2 |
+---------+---------------+---------------+
它们具有一对多的关系,图像表具有属性表的外键。 我想执行一个查询,该查询选择一个属性,然后选择该属性的单个图像。 我正在尝试使用的查询是
SELECT * FROM properties p
JOIN (SELECT * FROM images im LIMIT 1)
ON im.propertyId = p.propertyId;
它不起作用。 它也不返回错误。
如果要返回所有行,则查询将变为:
SELECT * FROM properties p
JOIN images im
ON im.propertyId = p.propertyId;
使用LIMIT 1
您只能从图片表中返回一行,因此您对行数有所限制
编辑
发表评论后:
这样,您将获得链接到您的媒体资源的第一张图片。
SELECT p.*,
(SELECT im.mage
FROM images im
WHERE im.propertyId = p.propertyId
AND NOT EXISTS (
SELECT 'NEXT'
FROM images im2
WHERE im.propertyId = im2.propertyId
AND im2.imageId > im.imageId)
)
FROM properties p;
请尝试以下查询,
SELECT * FROM properties p
JOIN images im
ON im.propertyId = p.propertyId
where p.propertyTitle = '1 acre land'
LIMIT 1
我们可以使用两个联接来解决此问题。 首先,如您在问题中怀疑的那样,将属性表加入到图像表。 然后,执行其他操作以加入子查询,该子查询为每个属性找到第一张图像。
SELECT
p.propertyId,
p.propertyTitle,
i1.image
FROM properties p
INNER JOIN images i1
ON p.propertyId = i1.propertyId
INNER JOIN
(
SELECT propertyId, MIN(imageId) AS min_imageId
FROM images
GROUP BY propertyId
) i2
ON i1.propertyId = i2.propertyId AND
i1.imageId = t2.min_imageId;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.