我对可能是一个相当简单的SQL语句有一些问题 - 不幸的是,我的技能并没有达到这个目的,我无法理解它!
例如,我有以下表格:
预订记录可能有一个客户的许多预订,它们通过'labelno'链接。
我想选择最后预订但未预订的客户。即该客户已于去年本月预订,但今年尚未预订。
我只选择了这两种情况,例如:
Select client_.title,
client_.initial,
client_.surname,
client_.labelno,
client_.email,
booking_record_.bookingdate
From booking_record booking_record_
Inner Join client client_ On booking_record_.labelno = client_.labelno
Where client_.email Not Like ''
And Date_Format(booking_record_.bookingdate, '%m') = ?Param1
And Date_Format(booking_record_.bookingdate, '%Y') = Year(AddDate(Now(), Interval -1 Year))
Group By client_.labelno
我快速浏览了一下视图,但是在报表设计器中使用它似乎不支持视图(或者至少在设计时不支持视图)。是否有可能在不使用视图的情况下得到我需要的东西?
谢谢,丹尼尔。
答案 0 :(得分:1)
使用:
SELECT c.title,
c.initial,
c.surname,
c.labelno,
c.email,
br.booking date
FROM CLIENT c
JOIN BOOKING_RECORD br ON br.labelno = c.labelno
AND br.bookingdate BETWEEN STR_TO_DATE(?Param1, '%Y-%m-%d')
AND STR_TO_DATE(?Param2, '%Y-%m-%d')
WHERE c.label_no NOT IN (SELECT t.label_no
FROM BOOKING_RECORD t
WHERE br.bookingdate BETWEEN STR_TO_DATE(?Param3, '%Y-%m-%d')
AND STR_TO_DATE(?Param4, '%Y-%m-%d')
在MySQL中,NOT IN
和LEFT JOIN/IS NULL
比NOT EXISTS
快。对于more information, see this link for details。
答案 1 :(得分:0)
Select c.title,
c.initial,
c.surname,
c.labelno,
c.email
from
client c
where exists (select * from booking_record where labelno=c.labelno
and bookingdate between @start1 and @end1)
and not exists (select * from booking_record where labelno=c.labelno
and bookingdate between @start2 and @end2)
这将start1和end1作为去年预订窗口的日期,以及今年的start2和end2,并且应该返回第一个列表中的所有客户端列表,而不是第二个列表中的所有客户端列表。对不起,如果变量格式代码对你来说是错误的,那我已经有一段时间了,因为我已经完成了MySQL,但其余的应该没问题 - 你想要在where子句中进行双重EXISTS检查。
答案 2 :(得分:0)
由于我对mySQL不起作用,并且不知道所有日期函数,所以我刚刚使用了以下日期的描述。尝试以这种方式编写查询,而不是使用表列上的函数,因为这可能会妨碍索引的使用。
SELECT
C.title,
C.initial,
C.surname,
C.labelno,
C.email,
BR.bookingdate
FROM
Booking_Record BR1
INNER JOIN Client C ON
C.labelno = BR.labelno AND
C.email NOT LIKE ''
WHERE
BR1.bookingdate >= <jan. 1st last year> AND
BR1.bookingdate < <feb. 1st last year> AND
NOT EXISTS
(
SELECT
*
FROM
Booking_Record BR2
WHERE
BR2.labelno = BR1.labelno AND
BR2.bookingdate >= <jan. 1st this year> AND
BR2.bookingdate < <feb. 1st this year>