我想从一些表中获得一些列。我的用户有问题。 userId
可以为0,但我希望将其作为null
返回。当我使用这个简单的union语句执行它时,结果如下所示:
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;
预期结果:
43 NULL NULL 2013-01-10 02:00:00 2013-01-10 02:30:00 3
真实结果:
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
问题: 该语句为在数据库中注册的每个worker返回一行。我该如何解决?
表架构:
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)
)
答案 0 :(得分:3)
您的第二个查询仍然需要应用加入条件:
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