如果不在另一个查询中,请选择ROW

时间:2013-01-21 15:34:07

标签: php mysql sql web

我有这个问题:

query 1 = 
SELECT emp.employeId,emp.nom,emp.prenom,msg.note,msg.quelleDate, emp.remarques, emp.autonome, embauche.actif as embaucheActif, embauche.embId, 'M' as source 
FROM employes emp 
LEFT JOIN messages msg ON msg.employeId = emp.employeId 
LEFT JOIN embauche ON embauche.employeId = emp.employeId 
WHERE emp.actif = 1 
AND msg.quelleDate BETWEEN '2013-01-01' AND '2013-01-31' 

UNION 

SELECT emp.employeId,emp.nom,emp.prenom,msg.note,msg.quelleDate, emp.remarques, emp.autonome, embauche.actif as embaucheActif, embauche.embId, 'A' as source 
FROM employes emp 
LEFT JOIN messagesautre msg ON msg.employeId = emp.employeId 
LEFT JOIN embauche ON embauche.employeId = emp.employeId 
WHERE emp.actif = 1 
AND msg.quelleDate BETWEEN '2013-01-01' AND '2013-01-31' 

ORDER BY nom,prenom,quelleDate

这个查询

query2 = select nom,prenom from employes where actif = 1;

我正试图让query2中没有出现query1

select employeId,nom,prenom from employes where actif = 1 AND employeId in ( query1 ); 人员

我试过

query1

但当然这不起作用,因为{{1}}返回超过1列

使用MySQL查询可以做到这一点吗?或者我将不得不编写PHP算法来执行此操作?

2 个答案:

答案 0 :(得分:2)

您在第一个查询中对表的第二个查询中的条件。员工表中是否有重复的名称和名字?如果没有,您只需将以下内容添加到每个where子句中:

and emp.Active = 1

如果ActifActive相同,那么您将永远不会获得任何行。

更通用的方法是将以下内容添加到where子句中:

and not exists (select 1 from employes emp2 where emp2.prenom = emp.prenom and emp2.nom = emp.prenom)

答案 1 :(得分:2)

这样做很简单:

select nom,prenom from employes AS emp 
LEFT JOIN embauche AS emb  
ON emp.employeID = emb.employeID
LEFT JOIN messages AS msg
ON emp.employeID = msg.employeID
where actif <> 1
AND msg.quelleDate NOT BETWEEN '2013-01-01' AND '2013-01-31';

示例数据:

CREATE TABLE employes (
  employeId int auto_increment primary key,
  nom varchar(30),
  prenom varchar(30),
  remarques longtext,
  autonome longtext
  );

CREATE TABLE messages (
  messagesID int auto_increment primary key,
  employeId int,
  quelleDate DATE,
  note longtext

  );

CREATE TABLE embauche(
  embId int auto_increment primary key,
  employeID int,
  actif int
  );

INSERT INTO employes (nom,prenom,remarques,autonome)
VALUES ("hollande", "francois", "24th President of France", "?"),
("Sarkozy", "Nicolas", "23th President of France", "?");


INSERT INTO messages (employeId,quelleDate,note)
VALUES (1, now(),"jlkjlkahkjhkj"),
(2,NOW() - INTERVAL 365 DAY,"jlkjlkahkjkjjhajhjheuioueoijhkj");


INSERT INTO embauche (employeId,actif)
VALUES (2, 2),
(1,1);

Demo sql fiddle