我目前有一个类似于以下内容的查询
SELECT
p.*, total
FROM
scripts p
LEFT JOIN
(SELECT script_id, COUNT(*) as total FROM creator_log WHERE created_date > timestampadd(hour, -6, now()) GROUP BY script_id) p2
ON
p.script_id = p2.script_id
WHERE
(p2.total < 1 OR p2.total IS NULL)
AND
p.script_status = '1'
ORDER BY
p.script_id DESC
LIMIT
1
然后我如何根据返回的count()
script_id
products
从另一个名为p.script_id
的表中找到count
,然后确保SELECT
p.*, total, active_total
FROM
scripts p
LEFT JOIN
(SELECT script_id, COUNT(*) as total FROM creator_log WHERE created_date > timestampadd(hour, -6, now()) GROUP BY script_id) p2
ON
p.script_id = p2.script_id
RIGHT JOIN
(SELECT script_id, COUNT(*) as active_total FROM products WHERE last_used < timestampadd(hour, -6, now()) AND status = 1) p3
ON
p.script_id = p3.script_id
WHERE
(p2.total < 1 OR p2.total IS NULL)
AND
(p3.active_total < 5 or p3.active_total IS NULL)
AND
p.script_status = '1'
ORDER BY
p.script_id DESC
LIMIT
1
}小于5?
我认为我应该做某种正确的加入?
编辑我尝试了以下无效
{{1}}
答案 0 :(得分:1)
不需要像这样进行内连接或完全连接(不是右或左):
SELECT p.*, total
FROM scripts p
LEFT JOIN
(SELECT script_id, COUNT(*) as total
FROM creator_log
WHERE created_date > timestampadd(hour, -6, now())
GROUP BY script_id) p2
ON p.script_id = p2.script_id AND p2.total < 1
JOIN
(SELECT script_id, COUNT(*) as active_total
FROM products
WHERE last_used < timestampadd(hour, -6, now()) AND status = 1) p3
ON p.script_id = p3.script_id AND p3.active_total < 5
WHERE p.script_status = '1'
ORDER BY p.script_id DESC
LIMIT 1
注意,您可以向ON子句添加多个要求,从而使您的where子句更简单,更容易理解。
这是如何工作的:因为p3上的连接是两个脚本中的完整连接元素,并且p3必须存在。这使得p3中的元素如您所描述的那样“必需”。