2016-09-30 43 views
0

我有這兩個表Mysql的獨家左邊的一個連接到許多關係

facilities 
+----+--------------------------------------+--------------+-------+------+------------+------------+ 
| id | name         | category  | image | cust | created_at | updated_at | 
+----+--------------------------------------+--------------+-------+------+------------+------------+ 
| 1 | Bar         | hotel  |  |  | NULL  | NULL  | 
| 2 | Minibar in alle Zimmer    | hotel  |  |  | NULL  | NULL  | 
| 3 | Snack restaurant      | hotel  |  |  | NULL  | NULL  | 
| 4 | Grillroom       | hotel  |  |  | NULL  | NULL  | 
+----+--------------------------------------+--------------+-------+------+------------+------------+ 

表 - 2

resortfacilities 

+----+------+---------------------+---------------------+------+ 
| id | f_id | created_at   | updated_at   | h_id | 
+----+------+---------------------+---------------------+------+ 
| 42 | 4 | 2016-09-21 13:17:27 | 2016-09-21 13:17:27 | 35 | 
| 59 | 1 | 2016-09-22 10:23:27 | 2016-09-22 10:23:27 | 38 | 
| 60 | 4 | NULL    | NULL    | 38 | 
+----+------+---------------------+---------------------+------+ 

而且我跑這下面的SQL

SELECT 
facilities.id, 
facilities.`name`, 
facilities.image, 
resortfacilities.h_id 
FROM 
facilities 
LEFT JOIN resortfacilities ON facilities.id = resortfacilities.f_id 
WHERE 
resortfacilities.f_id IS NULL AND 
facilities.category = 'hotel' OR 
resortfacilities.h_id <> 35 

與期望得到以下結果

+----+---------------------------+-------+------+ 
| id | name      | image | h_id | 
+----+---------------------------+-------+------+ 
| 4 | Grillroom     |  | 38 | 
| 2 | Minibar in alle Zimmer |  | NULL | 
| 3 | Snack restaurant   |  | NULL | 
+----+---------------------------+-------+------+ 

與出屬於h_id 35的值,但我最終

+----+---------------------------+-------+------+ 
| id | name      | image | h_id | 
+----+---------------------------+-------+------+ 
| 1 | Bar      |  | 38 | 
| 4 | Grillroom     |  | 38 | 
| 2 | Minibar in alle Zimmer |  | NULL | 
| 3 | Snack restaurant   |  | NULL | 
+----+---------------------------+-------+------+ 

我想知道如何得到這一結果?

+1

嘗試把括號內爲表達** resortfacilities.f_id IS NULL和 facilities.category = '酒店' OR resortfacilities.h_id <> 35 ** – StanislavL

+0

它看起來對我來說,你的數據不是適當規範化。例如,爲什麼created_at出現在兩個表中? – e4c5

+0

最有可能'WHERE facilities.category = '酒店' AND( resortfacilities.f_id IS NULL OR resortfacilities.h_id <> 35)' – Serg

回答

0

使用下面的腳本(用於獲得上述結果)。

SELECT 
f.id, 
f.`name`, 
f.image, 
r.h_id 
FROM 
facilities f 
LEFT JOIN resortfacilities r ON f.id = f.f_id AND r.h_id <> 35 
WHERE f.category = 'hotel' 
+0

檢查你的別名 – Serg

+0

@serg更新..感謝通知。 –