该子查询为您提供每个 distinct 的计数prop_id
。您只能将一个计数值分配给prop_count
。如果您打算更新prop_count
与 prop_ids 对应的 in 多行,则需要将相关子查询添加到更新中,以将prop_id
intbl_bookings
与相应的prop_id
in相关联tbl_listings
。
当我更多地考虑您的问题时,我想知道您是否打算插入一个空的 tbl_listings 表而不是更新。您可以使用以下命令执行此操作:
INSERT INTO tbl_listings(prop_id,prop_count)
SELECT prop_id, COUNT(*) as prop_count
FROM tbl_bookings
GROUP BY prop_id
如果您真的打算更新并假设每个prop_id
都存在于您的tbl_listings
表中,您可以发出以下更新:
UPDATE tbl_listings
SET prop_count=(SELECT COUNT(*)
FROM tbl_bookings AS TB
WHERE TB.prop_id=TL.prop_id)
FROM tbl_listings AS TL
如果您想tbl_listings
通过插入新的 prop_idstbl_bookings
及其各自的计数来更新,您可以执行以下操作:
INSERT INTO tbl_listings(prop_id,prop_count)
SELECT prop_id, COUNT(*) as prop_count
FROM tbl_bookings AS TB
WHERE NOT EXISTS(SELECT prop_id -- Insert only new prop_ids/counts
FROM tbl_listings AS TL
WHERE TL.prop_id=TB.prop_id)
GROUP BY prop_id