我正在尝试将一个非重复的job_id插入到review_job中,但是子句和连接无法正常工作。
请考虑此查询
INSERT INTO review_jobs (job_id)
SELECT B.JOB_ID FROM (
SELECT A.job_id AS JOB_ID FROM jobs A
LEFT JOIN review_jobs RJ ON A.job_id=RJ.job_id
WHERE RJ.job_id IS NULL
HAVING A.post_date=MIN(A.post_date)
LIMIT 1
) B;
如果我删除了having子句,则上面的查询带来了相同的job_id,它已经存在于review_jobs中,否则它不会插入。我的目标是将最早的工作放在review_jobs表中。
答案 0 :(得分:2)
要查找最早的作业,您可以使用order by
:
insert review_jobs
(job_id)
select j.job_id
from jobs j
left join
review_jobs rj
on j.job_id = rj.job_id
where rj.job_id is null
order by
j.post_date
limit 1
答案 1 :(得分:2)
你想要这个吗?
来自尚未处于review_jobs
的工作的最旧job_id
如果是这样,试试这个
INSERT INTO (job_id)
SELECT A.job_id
FROM jobs A
WHERE NOT EXISTS (SELECT *
FROM review_jobs RJ
WHERE A.job_id=RJ.job_id)
ORDER BY A.post_date
LIMIT 1;
答案 2 :(得分:2)
有几点:
INSERT ... SELECT
ORDER BY
和LIMIT
的组合来获取前n个或最后n个记录。所以查询变为:
INSERT INTO review_jobs (job_id)
SELECT A.job_id
FROM jobs A
LEFT JOIN review_jobs RJ ON A.job_id = RJ.job_id
WHERE RJ.job_id IS NULL
ORDER BY A.post_date
LIMIT 1
答案 3 :(得分:0)
HAVING是一个组选择器,您的语句中没有GROUP BY。请尝试以下方法:
...WHERE RJ.job_id IS NULL ORDER BY A.post_date ASC LIMIT 1
您也可以使用子查询,例如
...WHERE RJ.job_id IS NULL AND NOT EXISTS (SELECT job_id FROM jobs WHERE post_date < A.post_date)