我有两张桌子。
画; ID, 艺术家, 标题
runlog; VideoID,'加入视频.ID 日期时间
我想在视频表上运行查询,不包括三个条件的记录。 (作为例子。我有多个条件,但如果我得到一些帮助,我可能会把其他一切都搞清楚。
这让我得到了第一个结果要求,但我觉得它写得更好。
SELECT ID,Artist, Title FROM
videos join runlog on runlog.videoID = videos.id
where
(select COUNT(*) from runlog where datetime > DATEADD(hh,-12,GETDATE())
and runlog.videoID = videos.id) = 0
order by Artist, Title
第二个要求我无法弄清楚如何将它们放在同一个查询中。
答案 0 :(得分:0)
SELECT ID, Artist, Title
FROM videos v join runlog l on l.videoID = v.id
WHERE
-- 1. All in past hour will not show
datetime < DATEADD(hour,-1,GETDATE())
-- 2.
and not exists
( select 1
from videos v2 join runlog l2 on l2.videoID = v2.id
where v2.Artist = v1.Artist and datetime > DATEADD(hour,-1,GETDATE())
)
-- 3.
and not exists
(
select 1
from
(
select count(1) recordCount
from videos v3 join runlog l3 on l3.videoID = v3.id
where v3.Artist = v1.Artist and datetime > DATEADD(hour,-24,GETDATE())
)
where recordCount>=3
)
order by Artist, Title
OR
SELECT ID, Artist, Title
FROM videos v join runlog l on l.videoID = v.id
WHERE
-- 1. All in past hour will not show
datetime < DATEADD(hour,-1,GETDATE())
and v1.Artist in
(
-- 2.
select Artist
from videos v2 join runlog l2 on l2.videoID = v2.id
where datetime > DATEADD(hour,-1,GETDATE())
union all
-- 3.
select Artist
from videos v3 join runlog l3 on l3.videoID = v3.id
where datetime > DATEADD(hour,-24,GETDATE())
group by v3.Artist having count(1) >= 3
)
答案 1 :(得分:0)
SELECT ID, Artist, Title
FROM Videos V
WHERE V.ARTIST NOT IN
(SELECT V2.Artist
FROM RunLog R
INNER JOIN Videos V2 ON V2.ID = R.VideosID
WHERE dateTime >= DateAdd(hh, -1, GetDate())
UNION ALL
SELECT V3.Artist
FROM RunLog R
INNER JOIN Videos V3 ON V3.ID = R.VideosID
WHERE dateTime >= DateAdd(hh, -24, GetDate())
GROUP BY V3.Artist
HAVING Count(*) >= 3
)
)
使用NOT EXISTS
SELECT ID, Artist, Title
FROM Videos V
WHERE NOT EXISTS
(SELECT 1
FROM RunLog R
INNER JOIN Videos V2 ON V2.ID = R.VideosID
WHERE dateTime >= DateAdd(hh, -1, GetDate())
AND V2.Artist = V.Artist
UNION ALL
SELECT 1
FROM RunLog R
INNER JOIN Videos V3 ON V3.ID = R.VideosID
WHERE dateTime >= DateAdd(hh, -24, GetDate())
AND V3.Artist = V.Artist
GROUP BY V3.Artist
HAVING Count(*) >= 3
)
)
条件2将自动满足条件1
答案 2 :(得分:0)
此查询显式强制执行后两个约束,第一个隐式执行(强制第二个隐式强制执行第一个约束)。这是未经测试的,但它应该让你走上正确的轨道。
select ID, Artist, Title
from Video
where Artist not in (
select V.Artist
from Video V, Runlog R
where V.ID = R.VideoID
and R.datetime > dateadd(hour, -1, getdate())
union
select V.Artist
from Video V, Runlog R
where V.ID = R.VideoID
and R.datetime > dateadd(hour, -24, getdate())
group by V.Artist
having count(*) > 2
);