2017-01-30 62 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) 

如果你想計數包括所有項目,那麼你應該照顧的空值。