我正在写一个SQL查询,但我陷入了困境,无法弄清楚如何解决这个问题。首先看看下面的查询:
SELECT user_id, COUNT(*) as count
FROM hwc_attend
WHERE at_id IN
(SELECT evdet_id
FROM eve_detail
WHERE evdet_id IN (SELECT at_id FROM hwc_attend WHERE attendstate=1 )
AND location <> ''
AND evdet_id > 999
AND location NOT IN (SELECT ASIN FROM pReviews )
)
GROUP BY user_id
此查询工作正常,但结果不是必需的,因为部分SELECT ASIN FROM pReviews
应该像SELECT ASIN FROM pReviews where cID={place current value of "location" field from table eve_detail here
。
为了更好地理解,这里是错误的查询:
SELECT user_id, COUNT(*) as count
FROM hwc_attend
WHERE at_id IN
(SELECT evdet_id **, location**
FROM eve_detail
WHERE evdet_id IN (SELECT at_id FROM hwc_attend WHERE attendstate=1)
AND location <> ''
AND evdet_id > 999
AND location NOT IN (SELECT ASIN FROM pReviews where cID=**location**)
)
GROUP BY user_id
很难解释..简而言之,我必须从表“eve_detail”中提取的结果中删除“location”值,该表也存在于列cID中的表“pReviews”中。
此外,如果有人可以将其转换为联接,那将是很好的。我需要两个查询来学习。
答案 0 :(得分:1)
将其翻译为联接会使用类似的东西。使用LEFT OUTER JOIN并检查NULL而不是NOT IN。我假设hwc_attend有一个名为id的唯一列,它在计数中用于获取不同的行。
SELECT ha1.user_id, COUNT(DISTINCT ha1.id) as count
FROM hwc_attend ha1
INNER JOIN eve_detail ed ON ha1.at_id = ed.evdet_id
INNER JOIN hwc_attend ha2 ON ed.evdet_id = ha2.at_id
LEFT OUTER JOIN pReviews pr ON ed.location = pr.ASIN AND cID = **location**
WHERE ha2.attendstate = 1
AND ed.location <> ''
AND ed.evdet_id > 999
AND pr.ASIN IS NULL
GROUP BY ha1.user_id
答案 1 :(得分:1)
更改
AND location NOT IN (SELECT ASIN FROM pReviews )
要
AND NOT EXISTS (SELECT ASIN FROM pReviews WHERE eve_detail.location = ASIN.cID )