0
請看看這兩個查詢:VS外部查詢
一:
INSERT INTO QandA (id, body, type, related, author_id, date_time)
SELECT NULL, :body, 0, NULL, :id, unix_timestamp
FROM (select count(*) as num_month,
count(date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 day))) as num_day,
count(date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 90 minute))) as num_90min
from QANDA
where author_id = :id and
type = 0 and
date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 50 day))
) a
WHERE num_month < 50 and num_day < 6 and num_90min < 1;
二:
INSERT INTO QandA (id, body, type, related, author_id, date_time)
SELECT NULL, :body, 0, NULL, :id, unix_timestamp
FROM dual
WHERE user_id = :id
AND NOT EXISTS (
SELECT count(*) AS num_month
count(date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 day))) as num_day,
count(date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 90 minute))) as num_90min
FROM QandA
WHERE author_id = :id and
type = 0 and
date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 50 day))
HAVING num_90min > 50
OR num_day > 6
OR num_month > 1
)
正如你看到他們兩個areidentical,只是第一個使用外部查詢和第二個使用having
條款。那麼哪種方法更好?還是有第三種方法比他們更好?