SQL加入where和limit

时间:2011-09-17 08:31:37

标签: sql

我想知道如何:

- Select 10 random jobs 
- Join the default jobs location name
- Join the default jobs sector name

对于每个加入表,如果作业有多个位置,我已添加_default

我有以下数据库结构。 enter image description here

我遇到的问题是此查询多次返回相同的作业。

SELECT j.job_id, j.job_name, j.job_uri, j.job_image1, s.section_name as section
FROM jobs j
LEFT JOIN job_sectors js ON j.job_id = js.job_id
LEFT JOIN sectors s ON s.sector_id = js.sector_id
WHERE j.job_featured = '1'
AND j.job_status = 'ENABLED'
ORDER BY RAND()
LIMIT 10

1 个答案:

答案 0 :(得分:2)

您可以在子查询中选择10个作业。如果一个作业有多个扇区,那么最终会有10行以上(但仍有10个作业。)

select  *
from    (
        select  *
        from    jobs
        where   jobs.job_featured = '1'
                and jobs.status = 'ENABLED'
        order by
                rand()
        limit 10
        ) as j
left join
        job_sectors js
on      js.job_id = j.job_id
left join
        sectors s
on      s.sector_id = js.sector_id