2017-06-02 82 views
-1

當我運行「高級搜索」查詢時,我希望能夠知道每條返回的符合條件的數量。例如,在此查詢,我得到它的名字與「A」和姓開始以「B」開頭的人:獲取滿足條件的數量

select case when (u.firstname like "A%") then 1 else 0 end + case when (u.lastname like "B%") then 1 else 0 end as criteria_nb, u.ID, firstname, lastname, picture from Users u where u.firstname like "A%" or u.lastname like "B%"; 

這裏是我的表用戶看起來像

ID 
firstname 
lastname 
picture 
nbr_children 

這工作正常。我只需要通過criteria_nb訂購結果,我將首先滿足滿足這兩個要求的用戶,然後是滿足一個要求的用戶。

現在的問題是如何在多個表上做到這一點。在這裏,我試圖讓有0至10個孩子和至少一個孩子出生在2017年。我有一個名爲「User_children_years_of_birth」表看起來像這樣的用戶:

| Field   | Type | Null | Key | Default | Extra | 
| user_id  | int(11) | YES |  | NULL |  | 
| year_of_birth | int(11) | YES |  | NULL |  | 

我第一次嘗試這樣的:

select case when (u.children_nbr >= 0 and u.children_nbr <= 10) then 1 else 0 end + case when ((yob.user_id = u.id and (yob.year_of_birth=2017))) then 1 else 0 end as nb_criteres, u.ID, firstname, lastname, picture from Users u join User_children_years_of_birth yob on (yob.user_id = u.id and (yob.year_of_birth=2017)) where (u.children_nbr >= 0 and u.children_nbr <= 10); 

這是行不通的。 INNER JOIN將使查詢返回符合BOTH條件的用戶。所以我試圖用這種語法(我最喜歡的實際)

select case when (u.children_nbr >= 0 and u.children_nbr <= 10) then 1 else 0 end + case when ((yob.user_id = u.id and (yob.year_of_birth=2017))) then 1 else 0 end as nb_criteres, u.ID, firstname, lastname, picture from Users u, User_children_years_of_birth yob where (u.children_nbr >= 0 and u.children_nbr <= 10) or (yob.user_id = u.id and (yob.year_of_birth=2017)); 

這會返回重複的結果,我不明白爲什麼。不過,我可以看到,如果用戶符合這兩個條件,則會以「2」作爲nb_criteria顯示一次,然後顯示爲「1」作爲nb_criteria。

現在我很困惑,因爲我首先認爲這兩個JOIN語法是等價的。所以,可以請你

1)我解釋這些結果

2)解釋我的區別,語法

3)告訴我如何實現這一目標之間。

感謝

+0

見https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query – Strawberry

+0

我不確定你想要我做什麼有了這些信息。 !?!?! – Strawberry

+1

一個不同之處在於,第一個「yob.user_id = u.id和(yob.year_of_birth = 2017)」條件包含在JOIN中時的條件適用於所有結果。因爲在你的第二個結果中,WHERE包含「(u.children_nbr> = 0和u.children_nbr <= 10)或...」,只要滿足條件,就會滿足這個條件,這與第一個條件不一樣。 –

回答

0

這個結構應該幫助你

的存在是爲了檢查是否有至少1名兒童出生於2017年

具有計數 - 最大數量的孩子10

SELECT ... 
From table1 ... 
Join table2 ... 
Join table3 ... 
Where .... 
Exists(select 1 from tableforgettingkids where parent = mainqueryparentid and birthdateyear = 2017) 
Group by ... 
Having count(noofkids) < 11