我不太确定这是否是正确的方法,这是我的情况:
我目前正在尝试选择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查询混淆..
答案 0 :(得分: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
答案 1 :(得分: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,您就可以了)。之后,它与用户加入。当然,现在,这只小狗将返回每个嬉戏画廊,无论你有多少用户(hoorah!)。您可能希望在WHERE子句中限制用户(例如.- WHERE u.id = 123
)。否则,你将获得比你期望的更多的结果。那,或者做一个INNER JOIN就可以了。