我正在查询表1中基于子查询的日期列。 where子句中的子查询1从外键引用表获取描述,子查询2通过其他条件获取数据。
所以我的问题是,我有什么选择让这个查询变得更好?
SELECT count(*) AS non_saturday
FROM t_booking
WHERE p_id IN (
SELECT p_id
FROM p_detail
WHERE p_name IN ('A','B')
)
AND date_format(p_date, '%Y%m%d') IN (
SELECT DISTINCT CONCAT (
gregorian_ccyy
,gregorian_month
,gregorian_day
)
FROM m_gregorian_calendar1 c
WHERE c.day_of_the_week = (
SELECT day_id
FROM m_gregorian_day
WHERE day_name = 'SATURDAY'
)
AND c.gregorian_ccyy = '2012'
AND c.gregorian_month = '10'
)
答案 0 :(得分:2)
这可能不是你问题的直接答案,但是如果“星期六”你的意思是直接的星期六(而不是某个日历与日期和星期几之间有不同的映射),在我看来你可以简单地运行
SELECT count(*) AS non_saturday
FROM t_booking
JOIN p_detail ON (t_booking.p_id = p_detail.p_id AND p_name IN ('A','B'))
WHERE
DAYOFWEEK(p_date) = 7
AND MONTH(p_date) = 10
AND YEAR (p_date) = 2012
或更好地在p_date
字段上使用索引,
WHERE p_date BETWEEN "2012-10-01" AND "2012-10-31"
(但在日期字段中使用BETWEEN
时,请同时选中this answer)。