MySQL Subquery简单的SELECT问题

时间:2015-07-10 11:51:50

标签: mysql subquery

美好的一天,

我有以下查询。

SELECT `codeusage_id` FROM `panel_codeusage` 
WHERE `codeusage_exactdate` LIKE '2015-03%'

这给出了178个结果。

但我想知道哪些代码与活动预订相关联。 所以我写了这个子查询。

SELECT `codeusage_id` FROM `panel_codeusage` A
WHERE `codeusage_exactdate` LIKE '2015-03%' AND 
(SELECT `booking_cancel` FROM `panel_bookings` B
WHERE  A.`codeusage_link` = B.`booking_id` AND `booking_cancel` = 0)

这虽然没有给我任何结果。 谁能告诉我我做错了什么?

我已将查询编辑为:

SELECT `codeusage_id` FROM `panel_codeusage` A
WHERE `codeusage_exactdate` >= '2015-03-01' AND 
       codeusage_exactdate < '2015-04-01'
       EXISTS (SELECT 1
               FROM `panel_bookings` B
               WHERE  A.`codeusage_link` = B.`booking_id` AND
                     `booking_cancel` = 0
              );

仍无济于事。

当我直接在预订表中运行较小的查询以检查它是否有任何结果时,我得到168个结果

SELECT * FROM `panel_bookings` WHERE `booking_code` != '' AND `booking_day` LIKE '2015-03%' AND `booking_cancel` = 0 

所以我还在做错事......

1 个答案:

答案 0 :(得分:0)

您有一个返回EXISTS的子查询,MySQL将其解释为false。您需要SELECT `codeusage_id` FROM `panel_codeusage` A WHERE `codeusage_exactdate` >= '2015-03-01' AND codeusage_exactdate < '2015-04-01' AND EXISTS (SELECT 1 FROM `panel_bookings` B WHERE A.`codeusage_link` = B.`booking_id` AND `booking_cancel` = 0 );

LIKE

此外,请勿使用LIKE表示日期。 IIf([Enclosure]="Full Enclosure" Or [Enclosure]="Back Box only",[Hood Cut Size],"FALSE") 用于字符串,MySQL有很多与日期一起使用的函数。