in子句中的sql-mysql子查询

i34xakig  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(278)

我执行一个查询,它给我的结果是4,5,6。如果我直接在where in子句中的查询b中使用这个结果,它会再次给出完美的结果。但是如果我在查询c中同时使用这两个查询,它不会生成任何答案。
查询a

SELECT `region`.`district_id` 
FROM `region` 
LEFT JOIN `regional_owner` ON `regional_owner`.`r_id` = `region`.`id`
WHERE `regional_owner`.`email_id` = 'balajibarhate10@gmail.com';

产生o/p-4,5,6,我在下面使用
查询b

SELECT sum(`purchase`.`purchase_ammount`), `franchise`.`district_id`
FROM `purchase`
LEFT JOIN `franchise` ON `franchise`.`id` = `purchase`.`f_id`
WHERE `franchise`.`district_id` in ( 
         4,5,6
    )
    AND purchase.purchase_date BETWEEN Date_format(CURDATE(), "%Y-%m-01") AND CURDATE()
GROUP BY `franchise`.`district_id`

现在,我将上述两个查询合并为一个查询,如下所示
查询c

SELECT sum(`purchase`.`purchase_ammount`), `franchise`.`district_id`
FROM `purchase`
LEFT JOIN `franchise` ON `franchise`.`id` = `purchase`.`f_id`
WHERE `franchise`.`district_id` in ( 
    SELECT `region`.`district_id` 
    FROM `region` 
    LEFT JOIN `regional_owner` ON `regional_owner`.`r_id` = `region`.`id`
    WHERE `regional_owner`.`email_id` = 'balajibarhate10@gmail.com'
)

AND purchase.purchase_date BETWEEN Date_format(CURDATE(), "%Y-%m-01") AND CURDATE()
GROUP BY `franchise`.`district_id`

我不明白,哪一部分错了。请引导我。

mcvgt66p

mcvgt66p1#

你的左关节没有什么意义;左连接一个表,然后在where子句中使用该表,消除左连接引入的任何空值,有效地将其转换为内部连接
这也是编写查询的一种更简单的方法:

SELECT sum(`purchase`.`purchase_ammount`), `franchise`.`district_id`

FROM `purchase`
JOIN `franchise` ON `franchise`.`id` = `purchase`.`f_id`
JOIN `region` ON `region`.`district_id` = `franchise`.`district_id`
JOIN `regional_owner` ON `regional_owner`.`r_id` = `region`.`id`

WHERE
  `purchase`.`purchase_date` BETWEEN date_sub(curdate(),interval DAY(@date)-1 DAY) AND curdate() AND
 `regional_owner`.`email_id` = 'balajibarhate10@gmail.com'
GROUP BY `franchise`.`district_id`

如果你得不到结果,我就先把日期条款注解掉。还要注意的是,between是包容的,在处理日期时间时可能会很尴尬,例如 BETWEEN 2000-01-01 and 2000-01-31 遗漏了发生在例如200-01-31 12:34:56的记录,即使它们也发生在一月。。通常最好使用 >= 以及 < 除非你确定日期是离散的(没有时间)

相关问题