下面的sql查询有什么问题?

时间:2021-02-11 06:01:00

标签: mysql sql group-by inner-join mysql-workbench

我是 sql 初学者。任何人都请告诉我我的自定义查询的问题。

select * 
from Follow_My_Doct.tbl_hospital_registration h 
INNER JOIN Follow_My_Doct.tbl_subscribed_packages s 
      ON  s.hospitalId = h.id 
      AND s.active = 1 
      AND ( select max(sp.expireDate), sp.hospitalId 
            from Follow_My_Doct.tbl_subscribed_packages sp
            where sp.active = 1 
            group by sp.hospitalId ) 
where h.hospital_active = 1
<块引用>

错误代码:1241。操作数应包含 1 列

订阅表

hospital Id expireDate
145         2021-07-10
146         2021-06-10
147         2021-09-10
146         2021-10-10

3 个答案:

答案 0 :(得分:2)

您应该将该子查询与 max 和 group by 放在 INNER JOIN 子句中。

select * 
from Follow_My_Doct.tbl_hospital_registration h 
INNER JOIN ( select max(sp.expireDate) maxexpiredate, sp.hospitalId 
            from Follow_My_Doct.tbl_subscribed_packages sp
            where sp.active = 1 
            group by sp.hospitalId ) as s 
      ON  s.hospitalId = h.id 
where h.hospital_active = 1

由于我没有您的数据表,所以我创建了一个环境来使用表变量来测试该查询。下面的示例适用于 SQL Server,但查询适用于 MySQL,目前我的机器上还没有安装它。

declare @tbl_subscribed_packages TABLE(
  hospitalId int, 
  active bit, 
  expiredate datetime
)

declare @tbl_hospital_registration table(
 id int,
 hospital_active bit)

现在用数据填充表格:

insert @tbl_hospital_registration 
values (145,1),(146,1),(147,1)

insert @tbl_subscribed_packages 
values (145,1,'2021-07-10')
,(146,1,'2021-06-10')
,(147,1,'2021-09-10')
,(146,1,'2021-10-10')

然后,我针对这些数据测试查询

select * 
from @tbl_hospital_registration h 
INNER JOIN ( select max(sp.expireDate) maxexpiredate, sp.hospitalId 
            from @tbl_subscribed_packages sp
            where sp.active = 1 
            group by sp.hospitalId ) as s 
      ON  s.hospitalId = h.id 
where h.hospital_active = 1

请注意,在 INNER JOIN 中使用子查询作为视图,我应该为 max(expireDate) 列添加别名。 结果是:

<头>
id hospital_active 最大过期时间 医院ID
145 1 2021-07-10 00:00:00.000 145
146 1 2021-10-10 00:00:00.000 146
147 1 2021-09-10 00:00:00.000 147

这是你想要的吗?

答案 1 :(得分:0)

第 6 行有问题。在 AND 之后你应该有条件但你有子查询返回两个列值

答案 2 :(得分:-1)

您可以尝试以下操作 - 使用 row_number()

select * from
(
    select *,row_number() over(partition by s.hospitalId order by expireDate desc ) as rn from 
    Follow_My_Doct.tbl_hospital_registration h INNER JOIN Follow_My_Doct.tbl_subscribed_packages s 
    ON s.hospitalId = h.id 
    where h.hospital_active = 1 and s.active = 1 
)A where rn=1
相关问题