5

我不太确定这是否是正确的方法,这是我的情况:

我目前正在尝试选择 15 个画廊,然后通过 id 将其与用户表连接起来,但我也想从每个画廊中选择一张随机图片,但是据我所知,您不能将左连接(图片)限制为只选择一张随机图片而不进行子查询。

这是我到目前为止得到的,但它没有按应有的方式工作:

SELECT galleries.id, galleries.name, users.username, pictures.url 
FROM galleries 
LEFT JOIN users ON users.id = galleries.user_id 
LEFT JOIN pictures ON (
    SELECT pictures.url 
    FROM pictures 
    WHERE pictures.gallery_id = galleries.id 
    ORDER BY RAND() 
    LIMIT 1) 
WHERE active = 1 
ORDER BY RAND() 
LIMIT 15

我也尝试使用Active Record执行此操作,但在执行两次左连接后卡住了,是否可以在此处获取子查询:

$this->db->select('galleries.id, galleries.name, users.id as user_id, users.username');
$this->db->from('galleries');
$this->db->join('users', 'users.id = galleries.user_id','left');
$this->db->join('pictures','pictures.gallery_id = galleries.id AND','left');
$this->db->where('active',1);

我希望它不要乱,但我真的开始对所有的 sql 查询感到困惑..

编辑: 使用 CodeIgniter 的活动记录

4

2 回答 2

2

您可以在子查询中获取随机图片:

select 
    g.name, u.username,
    (select url from pictures p where p.gallery_id = g.gallery_id 
     order by rand() limit 1) as url
from galleries g
left join users u on g.user_id = u.id
where g.active = 1

根据您的评论,您可以在子查询中为每个图库选择一张图片。这是假设图片表有一个 ID 列。

select 
    g.name, u.username, p.url, p.name
from (
    select id, user_id, name,
        (select id from pictures p 
         where p.gallery_id = g.gallery_id 
         order by rand() limit 1) as samplepictureid
    from galleries
    where g.active = 1
) g
left join users u on g.user_id = u.id
left join pictures p on p.id = g.samplepictureid
于 2009-06-28T19:01:53.183 回答
1
SELECT
    g.id,
    g.name,
    u.username,
    p.url
FROM
    galleries g
    INNER JOIN (SELECT DISTINCT
         gallery_id,
         (SELECT url FROM pictures ss WHERE ss.gallery_id = s.gallery_id 
             ORDER BY RAND() LIMIT 1) AS url
     FROM
         pictures s) p ON
        g.id = p.gallery_id
    LEFT OUTER JOIN users u ON
        g.user_id = u.id
WHERE
    g.active = 1

此查询将出去并选择一个画廊,然后它将找到任何有图片的画廊(如果你想返回没有图片的画廊,请将 INNER JOIN 更改为 LEFT OUTER JOIN,你会没事的)。之后,它与用户一起加入。现在,当然,无论您拥有多少用户,这只小狗都会返回每个该死的画廊(哇!)。您可能希望在 WHERE 子句中限制用户(例如WHERE u.id = 123- )。否则,您将获得比预期更多的结果。那个,或者在它上面做一个 INNER JOIN。

于 2009-06-28T18:41:20.740 回答