我想随机选择一个“站点”记录,然后获取相关的“频道”。这是我尝试过的不起作用。请帮忙。谢谢!
SELECT A.*, B.*
FROM (
SELECT companies.company_name, sites.id
FROM sites
INNER JOIN company_sites ON company_sites.site_id = sites.id
INNER JOIN companies ON companies.id = company_sites.company_id
WHERE sites.active = 1
AND sites.stage_id = 5
GROUP BY sites.id
ORDER BY RAND()
LIMIT 1
)A
JOIN (
SELECT
channels.id
FROM channels
WHERE channels.site_id = A.sites_id
) B ON 1 = 1
答案 0 :(得分:1)
试试这个:
SELECT just the fields you need
FROM (
SELECT companies.company_name, sites.id id
FROM sites
INNER JOIN company_sites ON company_sites.site_id = sites.id
INNER JOIN companies ON companies.id = company_sites.company_id
WHERE sites.active = 1
AND sites.stage_id = 5
GROUP BY sites.id
ORDER BY RAND()
LIMIT 1
)A
join channels on channels.site_id = id
答案 1 :(得分:1)
顺便说一下,如果你只想要每个站点上的通道列表,你可以将它们连接成一个字段(而不是将它们放在不同的行上)。查询会更简单:
SELECT companies.company_name, sites.id, group_concat(channels.id) as channels
FROM sites
INNER JOIN company_sites ON company_sites.site_id = sites.id
INNER JOIN companies ON companies.id = company_sites.company_id
inner join channels on channels.site_id = sites.id
WHERE sites.active = 1
AND sites.stage_id = 5
GROUP BY sites.id
ORDER BY RAND()
LIMIT 1