我有职位和公司表,我想提取符合以下条件的20个职位:
我使用SELECT
尝试了以下UNION DISTINCT
,但问题是LIMIT 0,10
适用于整个结果集。我希望它适用于每个公司。
如果每个公司没有10个作业,那么查询应该返回它找到的所有作业。
SELECT c.name, j.title, j.`desc`, j.link
FROM jobs_job j
INNER JOIN companies_company c ON j.company_id = c.id
WHERE c.name IN ('Company1')
UNION DISTINCT
SELECT c.name, j.title, j.`desc`, j.link
FROM jobs_job j
INNER JOIN companies_company c ON j.company_id = c.id
WHERE c.name IN ('Company2')
ORDER by name, title
LIMIT 0,10
我是MySQL新手,所以意识到可能有一种更聪明的方法来代替UNION,所以任何改进建议都是值得欢迎的。
答案 0 :(得分:142)
引用the docs,
将ORDER BY或LIMIT应用于 个别SELECT,放置子句 在括起来的括号内 SELECT:
(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);
答案 1 :(得分:2)
根据Alex的回答并根据Joe的观察,以下内容应在SQLite中起作用:
SELECT * FROM
(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);
答案 2 :(得分:1)
@bioye 的回答需要我在 SQLite 上稍作修改。
SELECT * FROM
(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
SELECT * FROM
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);
答案 3 :(得分:0)