2014-06-20 38 views
2

我有兩個表MySQL的加入問題與在條件

Profile       Status 
    profile_id |name | active  status_id |profile_id|age 

我需要的狀態,在描述文件「活動」是1,狀態年齡大於10

該查詢返回時在PROFILE_ID是匹配

Select * from 
    status LEFT JOIN ON status.profile_id = profile.profile_id 

,但是當我把一個WHERE條件是不顯示任何

Select * from 
    status LEFT JOIN ON status.profile_id = profile.profile_id 
    where profile.active= 1 and status.age > 40 

左連接是正確類型的連接嗎?

+0

你錯過了第二個表名 – Phantom

+0

它是10還是40? –

+0

profile.enabled應該是profile.active – Ciaran

回答

0

正確profile.enabledprofile.active而且你也是table name失去了左加入。試試這個

SELECT * 
FROM status 
INNER JOIN profile ON status.profile_id = profile.profile_id 
WHERE profile.active = 1 
    AND status.age > 40 
+0

修復了類型錯誤 – meWantToLearn

+0

它的工作原理,但它甚至適用於內部連接。哪一個被推薦? – meWantToLearn

+0

根據我的suggesssion inner join,如果你想創建其配置文件的狀態? – Sadikhasan

0

試試這個。

SELECT * 
FROM Profile p, 
    Status s 
WHERE p.profile_id=s.profile_id 
    AND p.active=1 
    AND s.age>10 

此外請交叉檢查您的第二個查詢,它具有字段啓用,這在配置文件中不存在。

+0

你應該避免連接的語法,它是舊的,在各種數據庫(+ vs *等)上使用不同的語法,並且很難閱讀。 –

0

它似乎錯過了左連接子句中的表名。 在您的文章你問年齡大於10,在SQL命令是40

變化

Select * from 
    status LEFT JOIN ON status.profile_id = profile.profile_id 
    where profile.enabled = 1 and status.age > 40 

Select * from status LEFT JOIN profile ON status.profile_id = 
profile.profile_id where profile.active= 1 and status.age > 40 
1

你錯過了加入表名和profile.enabled應該profile.active試試這個:

Select * 
from 
     status 
     LEFT JOIN profile ON status.profile_id = profile.profile_id 
where 
     profile.active = 1 and status.age > 40 

OR

Select * 
from 
     status 
     LEFT JOIN profile ON status.profile_id = profile.profile_id and status.age > 40 
where 
     profile.active = 1 
+0

在這種情況下,由於您的WHERE條件,'LEFT JOIN'會隱式轉換爲INNER JOIN。查看@Rahul的答案。 – VMai

0

如果已經錯過了第二個表的表名。

您的查詢應該是這樣的:

缺少 '個人資料' 表格後
SELECT s.* FROM 
    status s LEFT JOIN profile p ON s.profile_id = p.profile_id 
    WHERE p.active= 1 and s.age > 40 
0

LEFT JOIN

SELECT * FROM 
     status LEFT JOIN profile 
     ON status.profile_id = profile.profile_id 
     AND profile.active= 1 AND status.age > 40