我有 2 张 table 。如何在mysql中获取左表中的总记录和右表中的匹配记录?我正在使用下面的查询,但它只会从两个表中获取匹配的记录。
SELECT post_id,COUNT(post_id) as pid,hostel_id,ht.user_id,hostel_name,
hostel_type,hostel_district,hostel_area,post_date,hostel_rent,hostel_respond,
h_contact_num,created_date,h_food_type
FROM hostels ht
left join histroy hr
ON ht.hostel_id =hr.post_id
WHERE ht.hostel_district=$city_code AND
ht.status='1' AND
hr.post_type='Hostel'
GROUP BY hr.post_id
ORDER by pid DESC
最佳答案
如果您想要每个组的总条记录数,则只需COUNT(*)
。如果您想要 histroy
表中与 hostels
表中的某些内容相匹配的记录数,那么您当前使用的 COUNT(post_id)
应该已经在这样做了。如果您想要 hostels
中与 histroy
中的任何内容都不匹配的记录数,那么您可以使用以下命令:
SUM(CASE WHEN post_id IS NULL THEN 1 ELSE 0 END) AS num_hostels_no_match
关于php - 如何在mysql中获取左表中的总记录和右表中的匹配记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41933169/