UNION ALL-JOIN如何限制为1

时间:2018-06-25 09:38:53

标签: php mysql

试图限制每行... 在我的查询中,我正在获取结果和用于结果的图像,但是如果存在例如: 会员有2张图片,它将显示2张图片,如果ttimages有30张照片,则将显示30张图片等

我要达到的结果是每个结果一个极限... 用一张图片而不是x的数量显示表中的一个结果,导致图像表中有多少张图片。

这是SQL ...

$sql = "
SELECT DISTINCT members.lastlogin as timeline_date, members.memusername as 
timeline_title, members.town as timeline_body, memberimages.images as 
timeline_img FROM members JOIN memberimages ON members.memid = 
memberimages.memid 
UNION ALL
SELECT DISTINCT ttages.dateadded as timeline_date, ttages.title as 
timeline_title, ttages.body as timeline_body, ttages_images.image as 
timeline_img FROM ttages JOIN ttages_images ON ttages.agesid = 
ttages_images.ageid
UNION ALL
SELECT DISTINCT sellit_listings.dateadded as timeline_date, 
sellit_listings.sittitlename as timeline_title, sellit_listings.sitcontent as 
timeline_body, sellit_images.images as timeline_img FROM sellit_listings JOIN 
sellit_images ON sellit_listings.listid = sellit_images.listid
UNION ALL
SELECT DISTINCT property_listings.dateadded as timeline_date, 
property_listings.paddress as timeline_title, property_listings.plistdiscript 
as timeline_body, property_images.image as timeline_img FROM 
property_listings JOIN property_images ON property_listings.propid = 
property_images.propid
UNION ALL
SELECT DISTINCT event_listings.dateadded as timeline_date, 
event_listings.eventtitle as timeline_title, event_listings.eventdescript as 
timeline_body, event_images.image as timeline_img FROM event_listings JOIN 
event_images ON event_listings.eventid = event_images.eventid
ORDER BY timeline_date DESC  LIMIT 70";

1 个答案:

答案 0 :(得分:1)

如果您希望每个成员,年龄等一个结果行,则按它们分组:

SELECT
  m.lastlogin as timeline_date,
  m.memusername as timeline_title,
  m.town as timeline_body,
  MIN(mi.images) as timeline_img 
FROM members m
JOIN memberimages mi ON m.memid = mi.memid
GROUP BY m.memid
UNION ALL
...

这是标准的SQL。不过,某些DBMS可能需要在所有列上使用伪聚合函数(即MIN(m.lastlogin)而不是m.lastlogin等),或将它们放在GROUP BY子句中。