Search code examples
mysqlsqlunioncreate-table

Issues with a select union SQL statement


I want to have some columns from some tables. I have a problem with the user. The userId can be 0, but I want to have it returned as null. When I do it with this simple union statement, the result looks like this:

SELECT 
      a.appointmentId, 
      u.prename AS user_prename, 
      u.lastname AS user_lastname, 
      a.start AS START , 
      a.end AS END , 
      w.workerId AS workerid 
FROM ios_appointments a 
     JOIN ios_user u
     JOIN ios_worker w 
     JOIN ios_partners p 
WHERE a.workerid_fk = w.workerid 
     AND w.partnerid_fk = p.partnerid 
     AND a.userid_fk = u.userid 
     AND p.code =  'DEMO6003' 
union 
select 
     a.appointmentId, 
     null, 
     null, 
     a.start AS START , 
     a.end AS END , 
     w.workerId AS workerid 
from ios_appointments a 
    JOIN ios_user u 
    JOIN ios_worker w 
    JOIN ios_partners p 
where 
    a.userid_fk = 0;

Expected result:

43  NULL    NULL    2013-01-10 02:00:00 2013-01-10 02:30:00 3

Real result:

43  NULL    NULL    2013-01-10 02:00:00 2013-01-10 02:30:00 1
43  NULL    NULL    2013-01-10 02:00:00 2013-01-10 02:30:00 2
43  NULL    NULL    2013-01-10 02:00:00 2013-01-10 02:30:00 3

Problem: The statement returns a row for each worker that is registered in the database. How can I fix it?

Table schema:

CREATE TABLE `ios_workinghours` (
  `workingHourId` int(11) NOT NULL AUTO_INCREMENT,
  `start` time DEFAULT NULL,
  `end` time DEFAULT NULL,
  `workerid_fk` int(11) NOT NULL,
  PRIMARY KEY (`workingHourId`),
  KEY `workerid_fk` (`workerid_fk`)
)

create table ios_worker (
    workerid int not null auto_increment,
    prename varchar(255),
    lastname varchar(255),
    avatar varchar(255),
    lineup varchar(255),
    languages varchar(255),
    partnerid_fk int not null,
    primary key(workerid),
    foreign key(partnerid_fk) references ios_partners(partnerid)
)

create table ios_user (
    userid int not null auto_increment,
    prename varchar(255),
    lastname varchar(255),
    phone varchar(255),
    email varchar(255),
    password varchar(255),
    primary key (userid)
)

create table ios_partners (
    partnerid int not null auto_increment,
    code varchar(255),
    partnerName varchar(255),
    street varchar(255),
    zipCode varchar(255),
    city varchar(255),
    languages varchar(255),
    workers varchar(255),
    lineup varchar(255),
    primary key(partnerid)
)

Solution

  • Your second query still needs the join criteria applied:

    FROM ios_appointments a 
         JOIN ios_user u
         JOIN ios_worker w 
         JOIN ios_partners p 
    WHERE a.workerid_fk = w.workerid 
         AND w.partnerid_fk = p.partnerid 
         AND a.userid_fk = u.userid 
         AND a.userid_fk = 0