以下 sql 查询中的问题是什么?

What is the issue in below sql query?

我是 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

Error Code: 1241. Operand should contain 1 column(s)

订阅table

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

您可以尝试以下方法 - 使用 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

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

您应该将带有 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

由于我没有您的数据 table,我构建了一个环境来使用 table 变量测试该查询。下面的示例适用于 SQL 服务器,但查询适用于 MySQL,目前我没有在我的机器上安装它。

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

declare @tbl_hospital_registration table(
 id int,
 hospital_active bit)

现在用数据填充 tables:

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 maxexpiredate hospitalId
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

这是你想要的吗?