Mysql group by和prefered field = 1在连接表中

时间:2016-12-10 16:41:11

标签: php mysql group-by inner-join

我有制造商的工作室,一个工作室可以有许多制造商,但只有一个官员。我想得到所有有制造商22的车间,但是如果他们有相同的缸,那么只能得到制造商正式的车间

我有2张桌子,第一个研讨会

id | name          | vat
-------------------------
 1 | name 1        | B12
 2 | name 2        | B12
 3 | name 3        | B12
 4 | name 4        | E98
 5 | name 5        | A99

第二次研讨会_制造商

id | workshop_id | manufacturer_id  | official
----------------------------------------------
 1 | 1           | 22               | 0               
 2 | 2           | 22               | 0
 3 | 3           | 22               | 1
 4 | 4           | 22               | 0
 5 | 5           | 22               | 1
 5 | 5           | 23               | 0
 5 | 5           | 24               | 0

我想获得独特的研讨会(按大桶分组),但如果有许多与此制造商合作的大桶的研讨会,我想获得官方研讨会(官方= 1)。

如果我执行此查询:

SELECT t1.*,t2.* FROM workshop t1
INNER JOIN workshop_manufacturer t2 ON t1.id=t2.workshop_id
WHERE t2.manufacturer.id = 22
GROUP bY t1.vat

我明白了:

id | name    | vat  | official | manufacturer_id 
-----------------------------------------------
 1 | name 1  | B12  | 0       | 22
 4 | name 4  | E98  | 0       | 22
 5 | name 5  | A99  | 1       | 22

我想要这个:

id | name    | vat  | official | manufacturer_id 
-----------------------------------------------
 3 | name 3  | B12  | 1      | 22
 4 | name 4  | E98  | 0      | 22
 5 | name 5  | A99  | 1      | 22

所有正式和非官方的工作坊,但优先考虑官方

2 个答案:

答案 0 :(得分:1)

这是优先级,而不是聚合。但它相当复杂。

以下内容为每个" vat"

获取研讨会的ID
select w.vat, max(case when w.official = 1 then w.id end) as official_id,
       max(w.id) as max_id
from workshop_manufacturer wm join
     workshop w
     on w.id = wm.workshop_id
group by w.vat;

有两个ID,一个是official可用,另一个是最大ID。

您现在可以在join中使用此功能来获取其余字段:

select w.workshop_id, w.name, w.vat,
       (official_id is not null) as official
from (select w.vat, max(case when w.official = 1 then w.id end) as official_id,
             max(w.id) as max_id
      from workshop_manufacturer wm join
           workshop w
           on w.id = wm.workshop_id
      group by w.vat
     ) v join
     workshop w
     on w.id = coalesce(official_id, max_id);

答案 1 :(得分:0)

试试这个。

SELECT t1.*,t2.* FROM workshop t1
INNER JOIN workshop_manufacturer t2 ON t1.id=t2.workshop_id 
GROUP bY t1.vat having t2.official = 1