MySQL查询使用WHERE连接表,包括匹配和非匹配

时间:2012-06-28 12:52:49

标签: php mysql join where

以下查询将选举人的ID与相应选民的投票意图相匹配,以查找某些标准。

    "   FROM electors,voting_intention 
WHERE electors.ID = voting_intention.elector 
AND electors.telephone > 0 
AND electors.postal_vote != 1 
AND (mosaic IN ('E1','E2','E3') 
OR (voting_intention.pledge IN ('C','P') 
AND  voting_intention.election != '2012-07-05'))  "

问题在于行AND (mosaic IN ('E1','E2','E3'),因为我们需要获取此信息,即使electors.ID和voting_intention.elector之间没有匹配项,因为此信息位于elector表中。

这样做的方法是将此行放在WHERE方程中。

3 个答案:

答案 0 :(得分:0)

应该这样做!

FROM electors e
FULL OUTER JOIN votin_intention i
   ON e.ID=i.elector
WHERE electors.telephone > 0  
AND electors.postal_vote != 1  
AND (mosaic IN ('E1','E2','E3')  
OR (voting_intention.pledge IN ('C','P')  
AND  voting_intention.election != '2012-07-05'))  " 

答案 1 :(得分:0)

您还可以执行左外连接以选择所有记录,而不仅仅是那些具有完整连接的记录

WHERE electors.ID(+) = voting_intention.elector 

类似的东西......(未经测试)

答案 2 :(得分:0)

这就是它:::

FROM electors,voting_intention WHERE electors.telephone > 0 AND electors.postal_vote != 1 AND (electors.mosaic IN ('E1','E2','E3') OR (electors.ID = voting_intention.elector AND voting_intention.pledge IN ('C','P') AND  voting_intention.election_date != '2012-07-05'))