mysql - Select records from table with inner join and where condition -


this first time use join method , don't well. have got tables($supportusertable , $supportuserperdepatable):

create table if not exists `razorphyn_support_user_departments` ( `id`                bigint(11)  unsigned    not null    auto_increment, `department_id`     bigint(11)  unsigned    not null, `department_name`   varchar(70)             not null, `user_id`           bigint(11)  unsigned    not null, `holiday`           enum('0','1')           not null    default '0', primary key (`id`), unique key(`department_name`,`user_id`) ) engine=myisam  default charset=utf8 auto_increment=0; 

and this

create table if not exists `razorphyn_support_users` ( `id`                bigint(11)  unsigned        not null auto_increment,  `name`              varchar(50)                 not null,    `mail`              varchar(50)                 not null,    `password`          varchar(200)                not null, `reg_key`           varchar(260)                not null, `tmp_password`      varchar(31)                 null, `ip_address`        varchar(50)                 not null, `status`            enum('0','1','2','3','4')   not null    default '3', `holiday`           enum('0','1')               not null    default '0', `mail_alert`        enum('no','yes')            not null    default 'yes', `assigned_tickets`  int(5)  unsigned            not null    default 0, `solved_tickets`    bigint(11)  unsigned        not null    default 0, primary key (`id`), unique key(`mail`) ) engine=myisam  default charset=utf8 auto_increment=55; 

and have writtenquery:

select a.id,a.name   ".$supportusertable."  inner join ".$supportuserperdepatable." b  on (a.id=b.user_id)    a.status='2' or b.department_id=?  order a.status asc, a.name asc 

basically want retrieve id , name first table where:

  • the status in first table 2
  • the department_id in second table equal value, in case select first table id equal second table user_id

reformulated:
query must match 1 of conditions:

  • a.status='2'=> retrieve a.name , a.id
  • a.department_id=value => retrieve a.id , a.name a.id=b.user_id

but can't retrieve record.

optimal query (for mysql only)

select distinct id,name   (   select a.id,a.name      ".$supportusertable."      a.status='2'    union (    select a.id,a.name         ".$supportuserperdepatable." b       left join  ".$supportusertable."           on a.id=b.user_id        b.department_id=? ,  a.id not null    ) )  tab  order tab.id asc, tab.name asc 

so got first raws status 2.

after union raws deparment_id=?(and check user exist).

after sort.

due mysql planner's issues likly optimal(if have indexes on status , deparment_id)


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -