从数据库中提取特定的条件数据

时间:2014-04-18 20:05:51

标签: mysql sql

我有三张桌子:

  1. " business" :字段(name,bus_id)。
  2. "分支" :字段(name,bus_id,bra_id,head_office_status)。
  3. " office" :字段(name,off_id,bra_id,main_state,sec_state)。
  4. 商业是主要的表,有许多分支机构,然后分支机构有许多办事处。 现在,我想写一个select查询来获取每个business_id的虚拟列state,我的条件如下:

    1. "(如果分支有 head_office_status = 1 ,那么获取 main_state!= NULL 的分支机构,否则选择 sec_state )作为州。
    2. (如果分支没有 head_office_status = 1 ,则获取head_office_status = 0的分支,然后是 main_state!= NULL 否则选择 sec_state )作为状态。
    3. 直到现在,我已写下以下查询:

      SELECT business.business_id,if(main_state != NULL and head_office_status=1, 
      main_state, if(sec_state != NULL and head_office_status=1,sec_state,
      if(main_state !=NULL, main_state, sec_state))) as state, from business
      left join branch on branch.bus_id = business.bus_id 
      left join office on office.bra_id = branch.bra_id where `business_name` 
      like '%';
      

      但是我看到每个企业都有很多记录,但我希望每条记录只有1个业务。

0 个答案:

没有答案