我需要有关此MySQL语句的一些帮助。在我的房地产应用程序中,我有一个“属性”表和一个“ propertyImages”表。在propertyImages表中,有一列标识用户选择哪个图像作为“主”图像,简称为“是”或“否”(我可以将其从“是” /“否”更改为“ 1” /”) 0“(如有必要)。主图像听起来很像-用户希望为此属性展示的照片。有时用户选择主属性图像,有时则不选择。实际上,有时他们根本不上传图像。
这是我的示例:
表1:属性
id | status | all other columns
------------------------
1 | published | blah
2 | published | blah
3 | published | blah
4 | published | blah
表2:propertyImages
id | propID | imgSrc | primaryImg
----------------------------------
52 | 2 | imgs/xxx.jpg | no
53 | 2 | imgs/xxx.jpg | no
54 | 2 | imgs/xxx.jpg | yes
55 | 3 | imgs/xxx.jpg | no
56 | 3 | imgs/xxx.jpg | no
57 | 3 | imgs/xxx.jpg | no
58 | 4 | imgs/xxx.jpg | no
请注意,属性1如何具有0张图像,属性2如何具有主图像(“是”),属性3和4不具有主图像(所有行均为“否”)。
我如何创建一个连接两个表并返回每个属性一行的SELECT语句(行中有主图像,如果没有主图像则为另一图像,如果没有图像则为NULL)。所选图像行的优先级变为...
我希望这成为表连接后的输出:
id | * | imgSrc | primaryImg
----------------------------------
1 | blah | NULL | NULL
2 | blah | imgs/xxx.jpg | yes
3 | blah | imgs/xxx.jpg | no
4 | blah | imgs/xxx.jpg | no
在mySQL语句中,我还需要包括几个条件。这是我到目前为止的内容:
SELECT *
FROM properties
LEFT JOIN propertyImages
ON properties.id = propertyImages.propertyID
WHERE properties.status = "published"
AND propertyImages.deleted = "no" -- Comment: not shown in table above
GROUP BY properties.id
我不知道是否应该使用“左联接”。我也使用“分组依据”来防止重复(我想要唯一的属性行,而不是每个图像一行),尽管我不确定“分组依据”是否是最有效的方法。我已经以一百万种不同的方式对此进行了测试,但没有得到我需要的结果。另外,我应该使用什么术语来解释/搜索?感谢任何可以提供帮助的人。
从几个子查询开始……这个子查询为每个属性选择最近上传的图像的ID。(这是具有最大值的图像id
。)对于的每个值,它要么返回一行,要么不返回任何行propID
。这意味着您可以LEFT JOIN
在不更改结果集中的行数的情况下进行操作。
SELECT MAX(id) id, propID
FROM propertyImage
WHERE deleted = 'no'
GROUP BY propID
这个选择最近上传的主映像的ID。是的,您只有一个主映像,但是可以。您的数据库不知道只有一个主映像,因此,如果碰巧有更多主映像,您只需选择一个即可。
SELECT MAX(id) id, propID
FROM propertyImage
WHERE deleted = 'no'
AND primaryImage = 'yes'
GROUP BY propID
接下来,将这两个子查询左连接到详细信息表。(https://www.db-fiddle.com/f/4Ra9UfxPTcYQAdSK2ETMPw/0)
SELECT something or other
FROM properties p
LEFT JOIN (
SELECT MAX(id) id, propID
FROM propertyImage
WHERE deleted = 'no'
AND primaryImage = 'yes'
GROUP BY propID
) primary ON p.propID = pri.propID
LEFT JOIN (
SELECT MAX(id) id, propID
FROM propertyImage
WHERE deleted = 'no'
GROUP BY propID
) other ON p.propID = other.propID
LEFT JOIN propertyImage i ON i.id = COALESCE(primary.id, other.id)
这里的技巧是COALESCE()
最后一个ON子句中的函数。如果不为空,则使用第一个参数;如果不为空,则使用第二个参数。因此,COALESCE(primary.id, other.id)
获取想要的图像的ID .. primary(如果存在),否则获取其他图像,或者为null。
最后,使您的SELECT
子句产生所需的列。
SELECT p.id, p.this, p.that, p.something, i.imgSrc, i.primaryImage
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句