2016-11-24 45 views
0

我想配置只有一个对我的当前查询的限制选择最大的ID。添加在最大的ID为SELECT查询

我有下面这在rextester一个链接显示的是什么,我想弄清楚的一个实际的例子。对不起,虽然它的错误...不知道当我创建示例时我做错了什么。

不管怎么说,你会看到:

INSERT INTO `profile_img` 
VALUES 
(1,24,'beach'), 
(2,55,'sandals'), 
(3,56,'hotel'), 
(4,55,'ocean'), 
(5,55,'corona'), 
(6,55,'tacos') 
; 

这是在我的profile_img表中的一些值。现在我的查询选择了此ON p.user_id = f.friend_one的所有配置文件映像。导致重复输出。它看起来像这样:

enter image description here

我只是希望它的输出

55  
56 

,并且适当调整最大ID img它。任何人都知道如何我只能SELECTprofile_img表的img列的最大id为匹配friend_one的user_id? ON p.user_id = f.friend_one

然而,有时用户不具有profile_img。以前我在查询中使用这个来获得那些没有的默认img。 (case when p.img <> '' then p.img else 'profile_images/default.jpg' end) as img

SELECT f.* 
     , p.* 
    FROM friends f 
    LEFT JOIN profile_img p 
    ON p.user_id = f.friend_one 
    WHERE f.friend_two = ? 
    AND f.status = ? 

http://rextester.com/RLXS27142

+1

你必须包括'DROP TABLE IF EXISTS '朋友'; DROP TABLE IF EXISTS 'profile_img';'上rextester http://rextester.com/ECAX16022 –

+0

@JuanCarlosOropeza感谢顶!我在看你那天做的那个。只是不知道这是必需的。 sqlfiddle太挑剔,速度太慢,所以我很高兴你给我看了这个消息。 – Paul

+1

这只需要MySQL,Postgres和SQL服务器不需要它 –

回答

1

如果我理解正确的话,你只是想最大id个人资料图片:

SELECT f.*, p.*, 
     COALESCE(p.img, 'profile_images/default.jpg') as profile_img 
FROM friends f LEFT JOIN 
    profile_img p 
    ON p.user_id = f.friend_one AND 
     p.id = (select max(p2.id) from profile_img p2 where p2.user_id = p.user_id) 
WHERE f.friend_two = ? AND f.status = ?; 
+0

嗯..我认为它可能工作,但我忘了把这个到我的问题。对于那些没有profile_img的人,我将配置文件img设置为默认值。在另一个查询我都这样了,但不知道如何将它添加到您所做的查询..'(情况下p.img <>“”,然后p.img别人的profile_images/default.jpg“ \t \t年底)为img' – Paul

+1

@Paul。 。 。我希望在'select'中将'coalesce(p.img,'profile_images/default.jpg')作为img'。 –

+0

是否这样? 'SELECT f。*,p。*,coalesce(p.img,'profile_images/default.jpg')as img',如果是这样,它仍然只显示一个55结果,而不显示没有配置文件的行的id 。 – Paul