2017-06-02 81 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