SQL LEFT JOIN有一个结果

时间:2017-04-30 08:39:47

标签: mysql sql join

我尝试执行LEFT JOIN,只返回一个结果。 我有3张桌子

ITEM:
==== some fields ====

ITEM_MEDIA_MAP:
item_id: foreign to item
media_id: foreign to media
featured: boolean

MEDIA:
==== some fields ====

我正在尝试获取项目的所有ITEM元素和每个缩略图。如果图像被标记为特征,则这是用户手动拾取的缩略图。

这是我的SQL查询

SELECT ITEM.title,  MEDIA.* 
FROM "ITEM"
LEFT JOIN (
    select * from ITEM_MEDIA_MAP
    where id in (
        select min(id) from ITEM_MEDIA_MAP group by item_id
    )
    ) as item_id
ON item_id = item.id
LEFT JOIN MEDIA
ON MEDIA.id = media_id
WHERE "ITEM.id" = 1 
ORDER BY ITEM.date ASC

此查询有效,只返回MAPing表中的一个结果。问题是我得到了第一个在数据库中写入的图像,我需要将图像标记为 features = 1 ,并且只有在我没有这样的图像才能获得第一个图像< / p>

我尝试了类似的东西

 SELECT ITEM.title,  MEDIA.* 
    FROM "ITEM"
    LEFT JOIN (
        select * from ITEM_MEDIA_MAP
        ORDER BY featured 
        ASC LIMIT 1
        ) as item_id
    ON item_id = item.id
    LEFT JOIN MEDIA
    ON MEDIA.id = media_id
    WHERE "ITEM.id" = 1 
    ORDER BY ITEM.date ASC

但是这个查询只返回JOIN的1个结果

3 个答案:

答案 0 :(得分:0)

当你处理:

我需要第一条记录,其中some_field = some_value,如果没有找到,则返回此other_record。

我通常会做下一个:

select fields
from (
      select fields, 0 as forder from my_table where first_condition limit 1
      union all
      select fields, 1 as forder from my_table where second_condition limit 1
     )
order by forder
limit 1 

然后,您可以确保返回的记录(如果存在)与所需条件匹配。

答案 1 :(得分:0)

你有这个:

select * from ITEM_MEDIA_MAP
    where id in (
        select min(id) from ITEM_MEDIA_MAP group by item_id
    )

但你需要这个:

select * 
from ITEM_MEDIA_MAP
order by featured desc, id
limit 0, 1

这将返回单行(最多),如果特征项存在,它将返回featured项,其中id项最小。如果它不存在,那么它将返回具有最小id的项目。另外,您可能只想select *代替select来优化查询所需的列。

答案 2 :(得分:0)

你可以联合这两个选项。 这样,您将有2个select语句,但不会为每个ITEM行进行子选择。通过以下方式:

/* All items which have featured=1 row, join with that row */
SELECT item.* , media.* 
from ITEMS item JOIN ITEM_MEDIA_MAP item_data ON item.id = item_data.item_id and item_data.featured = 1 JOIN MEDIA med ON med.id = item_data.media_id

UNION ALL 

/* All items which have max(featured)=0 row, join with min_id */
SELECT item.* , media.* 
from ITEMS item JOIN 
(select item_id, max(featured) as `featured`, min(id) as `min_id` from ITEM_MEDIA_MAP
group by item_id) as item_data ON item.id = item_data.min_id and item_data.featured = 0