2017-01-30 65 views
0

右表我有2个表。如何从左表和匹配的记录在mysql中的右表获得全部记录?我正在使用下面的查询,但它只会从两个表中获得匹配的记录。如何从左表总记录和匹配的记录形成的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 
+0

您可以显示一些样本数据来说明你想要的是什么?在“GROUP BY”查询的情况下,您对我的询问不清楚。 –

+0

你必须子句添加的所有列,除了'COUNT(POST_ID)为pid'您的小组。 –

+0

也许[这个问题](http://stackoverflow.com/questions/3453809/how-to-use-mysql-found-rows-in-php)将帮助你 –

回答

1

如果你想的记录每群组号,然后就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 
+0

的是,同样是“不匹配任何“或者仅仅是”不匹配的东西“ – Strawberry

0

不是一个真正的解决方案的详细图示的评论。 左(外)联接是摆脱宿舍,但聚合函数忽略空值的一切正确的方式。例如给予

drop table if exists t; 

create table t (id int, val int); 
insert into t values 
(1,1),(2,null),(3,3); 

此查询

MariaDB [sandbox]> select count(val) nonnullcount 
    -> from t; 

回报

+--------------+ 
| nonnullcount | 
+--------------+ 
|   2 | 
+--------------+ 
1 row in set (0.00 sec) 

如果你想计数包括所有项目,那么你应该照顾的空值。