有一个sql语句可以从此sqlfiddle
返回有价值的信息CREATE TABLE `civil`(
civil_id INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(25) ,
address_civil VARCHAR(40) NOT NULL ,
telephone VARCHAR(20 ) NOT NULL ,
email VARCHAR(30) NOT NULL ,
comment VARCHAR(35 ) NOT NULL ,
CONSTRAINT `uc_Info_civil` UNIQUE (`civil_id`)
);
CREATE TABLE `worker`(
worker_id INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(25) ,
address_worker VARCHAR(40) NOT NULL ,
departament VARCHAR(40) NOT NULL ,
age INTEGER NOT NULL ,
CONSTRAINT `uc_Info_civil` UNIQUE (`worker_id`)
);
CREATE TABLE `event`(
id_event INTEGER NOT NULL PRIMARY KEY,
type_event VARCHAR(25) ,
personID INT NOT NULL ,
date DATE NOT NULL ,
isWorker INT NOT NULL,
CONSTRAINT `uc_Info_event` UNIQUE (`id_event`)
);
ALTER TABLE `event` ADD INDEX (personID);
INSERT INTO `civil` VALUES ( 1, 'JOE','SOME ADDRESS', '5646464','joe@gms.com','no comment' );
INSERT INTO `civil` VALUES ( 2, 'MOE','SOME ADDRESS', '6776543','froe@ges.com','no comment' );
INSERT INTO `worker` VALUES ( 1, 'MARGE','STATES W54', 'finances',34);
INSERT INTO `worker` VALUES ( 2, 'SASHA','LIVER S 34', 'sells',23 );
INSERT INTO `event` VALUES (1,"type1", 1, '12-12-12',1);
做
SELECT a.*,
IF(a.Isworker = 1,c.name, b.name) AS personname
FROM event a
LEFT JOIN civil b
ON a.personid = b.civil_id
LEFT JOIN worker c
ON a.personid = c.worker_ID
返回
ID_EVENT TYPE_EVENT PERSONID DATE ISWORKER PERSONNAME
-----------------------------------------------------------------------------
1 type1 1 December, 12 2012 00:00:00+0000 1 MARGE
如何根据现场工作人员获取民事和工人表的所有数据(而不仅仅是姓名)?
答案 0 :(得分:4)
我可能会建议重新构建/更好地规范化表格......但是只要使用你拥有的东西,一种选择就是将你的isworker检查添加到join语句中。除此之外,您必须找到平民和工人之间的可比较字段,以便在IF()
声明中取消彼此,就像您用于人名。
SELECT *
FROM event a
LEFT JOIN civil b
ON a.personid = b.civil_id
AND a.Isworker != 1
LEFT JOIN worker c
ON a.personid = c.worker_ID
AND a.Isworker = 1