2013-02-28 66 views
3

數據的SELECT語句有一個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','[email protected]','no comment'); 
INSERT INTO `civil` VALUES ( 2, 'MOE','SOME ADDRESS', '6776543','[email protected]','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 

哪有我根據現場工作人員獲得所有民事和工作人員表的數據(不只是名字)?

回答

4

我可能會建議重新構造/更好地規範化表格......但只要處理好你的工作,一個選擇就是將isworker檢查添加到聯接語句中。除此之外,您必須在平民和工人之間找到可比較的領域,以便像用於人名那樣在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 
+0

我怎樣才能擺脫空?有沒有辦法避免它們? – cMinor 2013-02-28 20:45:33

+0

這就是你不得不使用'IF()'語句的地方,就像你爲人名所做的那樣。因此,例如,您可以選擇IF(a.Isworker = 1,c.name,b.name)作爲personname,IF(a.Isworker = 1,c.address_civil,b.address_worker)AS地址,.. 。「等等。 – Chains 2013-02-28 20:47:56

+0

由於'SELECT *'被忽略,如果你明確地選擇了你想要的字段,你可以通過使用'COALESCE()'來避免額外的空值,參見[mysql docs](http://dev.mysql.com/doc/refman /5.0/en/comparison-operators.html#function_coalesce) – 2013-02-28 21:48:17

相關問題