如何将连接限制为每条记录一个结果,以便 MYSQL
我目前有两张表,一张用于pages
(对象),一张用于images
(媒体)。
我想获取系统中所有页面的列表,并将单个图像记录连接到每个页面记录上。现在已经接近工作了,但它正在返回所有记录,而我只想取回一条记录。
我已经尝试了一些子查询+ Distinct,但还没有完全发挥作用。
谁能指出我正确的方向。我尝试过 group by,但排序后不起作用,因此返回了错误的图像。
SELECT title,
url,
media_file,
media_order
FROM ndxz_objects
LEFT JOIN ndxz_media ON ndxz_objects.id = ndxz_media.media_ref_id
WHERE `status` = 1
AND `section_id` = 2
GROUP BY title, url, media_file, media_order
ORDER BY ndxz_objects.ord, ndxz_media.media_order
I currently have two tables, one for pages
(objects) and one for images
(media).
I want to get a list of all the pages in the system, and join a single image record onto each page record. It's very close to working now, but it is returning all of the records, when I just want to get one back.
I've tried a few sub queries + Distinct, but not quite got it working yet.
Can anyone point me in the right direction. I've tried group by, but it doesn't work after doing the sort and therefore brings back the wrong image.
SELECT title,
url,
media_file,
media_order
FROM ndxz_objects
LEFT JOIN ndxz_media ON ndxz_objects.id = ndxz_media.media_ref_id
WHERE `status` = 1
AND `section_id` = 2
GROUP BY title, url, media_file, media_order
ORDER BY ndxz_objects.ord, ndxz_media.media_order
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您在
ndxz_media
中有一个名为id
的AUTO_INCRMENT
(例如),您可以获得MAX(id)
或子查询中的MIN(id)
,并对其进行连接。我认为这是可行的,因为 MySQL 允许将 GROUP BY 中未指定的列与聚合一起包含在内。在这里,这是子查询中的
media_file
和media_order
。假设将
media_order
作为高/低值而不是使用理论上的id
,内部子查询将如下所示。括号之外的所有内容都不会改变。首先单独运行子查询。它应该检索单个记录。然后,当放入括号时,连接应该可以正常工作。
If you have an
AUTO_INCREMENT
insidendxz_media
calledid
(for example), you can get theMAX(id)
orMIN(id)
in a subquery, and join against it.I think this works because MySQL allows columns not specified in the
GROUP BY
to be included along with the aggregate. Here, that'smedia_file
andmedia_order
in the subquery.Assuming
media_order
as a high/low value instead of using the theoreticalid
, the inner subquery would look like the following. Everything else outside the parens doesn't change.Run the subquery alone first. It should retrieve singular records. Then when placed into the parens, the join should work properly.
我没有发现该查询有效,这就是我最终使用的。
我从这里的组内聚合部分找到了这个这似乎是一组很好的sql示例
I didn't find that query worked, this is what I used in the end.
I found this from the within group aggrigates section here which seems like a good group of sql examples