多个mysql查询使用两个不同的表

时间:2014-09-19 19:08:57

标签: mysql

我在编写查询时遇到问题。我有两个表,我想从中提取数据,销售和电话。两个表中都有一列记录了电话号码,还有一个日期列。我可以很好地匹配JOIN来匹配销售,但是我也希望显示两个表中不匹配的条目。基本上在单个页面上显示与两个表匹配的行,然后单独显示与每个表不匹配的行。

这是JOIN查询:

SELECT 
   sales.*, 
   calls.* 
FROM `sales` 
JOIN `calls` 
    ON sales.TelephoneNo = calls.TelephoneNo 
WHERE (
       sales.OrderDate >= '$MyStartDATE' 
   AND sales.OrderDate <= '$MyEndDATE'
) AND (
       calls.CallDate >= '$MyStartDATE' 
   AND calls.CallDate <= '$MyEndDATE'
) ORDER BY sales.OrderDate

2 个答案:

答案 0 :(得分:0)

好吧,尝试使用&lt;&gt;运算符而不是=显示不匹配结果

SELECT 
   sales.*, 
   calls.* 
FROM `sales` 
JOIN `calls` 
    ON sales.TelephoneNo <> calls.TelephoneNo 
WHERE (
       sales.OrderDate >= '$MyStartDATE' 
   AND sales.OrderDate <= '$MyEndDATE'
) AND (
       calls.CallDate >= '$MyStartDATE' 
   AND calls.CallDate <= '$MyEndDATE'
) ORDER BY sales.OrderDate

<强>更新

如果你使用LEFT JOIN而不是JOIN它会有所不同吗?

试试此代码

SELECT sales.*, 
       calls.* 
FROM   `sales` 
       LEFT JOIN `calls` 
              ON sales.telephoneno <> calls.telephoneno 
WHERE  sales.orderdate >= '$MyStartDATE' 
       AND sales.orderdate <= '$MyEndDATE' 
       AND calls.calldate >= '$MyStartDATE' 
       AND calls.calldate <= '$MyEndDATE' 
ORDER  BY sales.orderdate 

答案 1 :(得分:0)

MySQL不支持完整联接,您需要将左右联接与联合组合

SELECT
    s.OrderDate,
    PhoneNumber,
    s.something fake,
    IF(c.PhoneNumber IS NULL, 'Sales', 'Both') match_from,
    IF(c.PhoneNumber IS NULL, 0, 1) has_match
FROM
    sales s
LEFT JOIN
    calls c
    USING (PhoneNumber)
WHERE
    s.OrderDate BETWEEN '$MyStartDATE' AND '$MyEndDATE'
UNION DISTINCT
SELECT
    c1.CallDate,
    PhoneNumber,
    'fake',
    IF(s1.PhoneNumber IS NULL, 'Call', 'Both'),
    IF(s1.PhoneNumber IS NULL, 0, 1)
FROM
    sales s1
RIGHT JOIN
    calls c1
    USING (PhoneNumber)
WHERE
    c1.CallDate BETWEEN '$MyStartDATE' AND '$MyEndDATE'
ORDER BY has_match