检查另一个表中是否存在id

时间:2015-05-08 18:56:59

标签: mysql sql

我现在有一个相当大的SQL查询:

SELECT a . * , ap . * , i . * , appstatus . * ,(SELECT SUM(rating) / count( case when rating > 0 then 1 end ) AS total_rating FROM review AS r WHERE r.applyid=a.applyid GROUP BY applyid) AS total_rating, (SELECT count(rating) FROM review AS r WHERE r.applyid=a.applyid GROUP BY applyid) as count
                FROM apply AS a, applicant AS ap, interest AS i, application_status AS appstatus, apply_tags as at
                WHERE a.applicantid = ap.applicantid
                AND a.applicantid = i.applicantid
                AND a.application_status_id = appstatus.application_status_id
                AND a.archive =  'false'
                AND a.jobid =27

我需要修改它,以便检查另一个表以查看是否存在a.applyid。

根据我现有的查询,我想修改它,以便只输出apply_tags表中没有数据的行。

我不确定将此功能集成到查询中的最佳方法。我应该使用加入吗?

我基本上想要添加一个这样的AND语句:

AND a.applyid NOT EXIST at.applyidat是apply_tags表)

我知道我做错了,但这是我想要做的事情的一个例子。

2 个答案:

答案 0 :(得分:2)

抱歉,我看到你已经选择了一个正确答案。但是你的查询远非完美。因此,如果您希望有一天优化它,这里只是一个想法如何:

SELECT a . * , 
ap . * , 
i . * , 
appstatus . * ,
r.total_rating, 
r.count
FROM apply AS a
LEFT JOIN (
  SELECT applyid, 
    SUM(rating) / SUM(IF(rating > 0,1,0)) AS total_rating,
    SUM(IF(rating > 0,1,0)) as count
  FROM review  
  GROUP BY applyid) AS r
ON r.applyid=a.applyid
LEFT JOIN applicant AS ap
ON a.applicantid = ap.applicantid
LEFT JOIN interest AS i
ON a.applicantid = i.applicantid
LEFT JOIN application_status AS appstatus
ON a.application_status_id = appstatus.application_status_id
LEFT JOIN apply_tags as at
ON a.applyid = at.applyid
WHERE a.archive =  'false'
   AND a.jobid =27
   AND at.applicantid IS NULL

小说明在原始查询中,您可以执行以下操作:

SELECT a . * , 
...,
(SELECT SUM(rating) / count( case when rating > 0 then 1 end ) AS total_rating FROM review AS r WHERE r.applyid=a.applyid GROUP BY applyid) AS total_rating,
(SELECT count(rating) FROM review AS r WHERE r.applyid=a.applyid GROUP BY applyid) as count
....

你问这种技术有什么问题?所以问题是MySQL将尝试在从a.table接收的每条记录上执行这两个SELECT。与我的LEFT JOIN相反,只需要一次所有记录。如果你在a中有100条记录,MySQL会调用100x2 = 200次子查询,而只有1次。

WHERE a.applicantid = i.applicantid vs LEFT JOIN i ON a.applicantid = i.applicantid几乎相同的原因。最后一个绝对是由MySQL优化的。第一个是非常缓慢和沉重的。如果你忽略MySQL的功能,它就是为它而发明的。你可以从所有5个表中SELECT *进入php数组并在php端执行所有逻辑。

你可以稍微google一下。例如:https://stackoverflow.com/a/2242015/4421474

答案 1 :(得分:1)

你的尝试非常接近。只需添加:

and not exists (select 1 from apply_tags where applyid = a.applyid)

以下是使用EXISTS / NOT EXISTS的文档:

https://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html