【问题标题】:repetitive values even with the usage of Distinct key word with inner join即使使用具有内部连接的 Distinct 关键字,也会出现重复值
【发布时间】:2023-03-27 09:35:01
【问题描述】:

学生桌。

|雷尼奥 |姓名 |姓名 |地址 |性别 |移动 |

预订表

bookID |雷尼奥 |代币号 |签到 |结帐

我正在尝试获取两个给定日期之间在场的女学生人数。我试图获取各自的值,但即使使用 distinct 关键字,它也会输出重复值。 我也尝试过使用 Union,但它仍然与 distinct 正好相反。

 SELECT  count(gender) FROM (SELECT  distinct regno from student where 
 gender = 'Male' union  SELECT Distinct regno from book)  x  LEFT OUTER JOIN 
 student a on x.regno = a.regno LEFT OUTER JOIN book b on x.regno = b.regno
  where checkIn >= '2015/7/23' AND checkOut <= '2015/7/31';

这是我尝试过的另一个

 SELECT count(gender) FROM (SELECT  distinct(regno), gender from student
   where  gender = 'Male' ) AS A inner JOIN book AS B On A.regno = B.regno            
    where   checkIn >= '2015/7/23' AND checkOut <= '2015/7/31';

【问题讨论】:

    标签: mysql inner-join distinct


    【解决方案1】:

    看起来您使一个简单的查询过于复杂。您需要做的就是加入表格并过滤日期和性别并应用计数。

    SELECT COUNT(DISTINCT s.regno) 
    FROM student s
    JOIN booking b on s.regno = b.regno
    WHERE s.gender = 'Female' 
      AND b.checkIn >= '2015/7/23' AND b.checkOut <= '2015/7/31';
    

    distinct 关键字确保每个学生在该期间有多个预订时只计算一次。如果您想计算所有预订,只需删除distinct

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 2012-11-12
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      相关资源
      最近更新 更多