mysql-表比较错误

时间:2012-02-03 15:50:41

标签: mysql

我有2张桌子,CAR_1和CAR_2。表CAR_1包含比CAR_2更多的列和更多记录。

运行以下查询会返回4647条记录:

(SELECT CAR_1.ID FROM CAR_1, CAR_2 WHERE 
CAR_1.ID = CAR_2.ID AND 
CAR_1.MODEL = CAR_2.MODEL AND
CAR_1.SYMBOL = CAR_2.SYMBOL AND
CAR_1.MAKE = CAR_2.MAKE AND
CAR_1.ORIGIN = CAR_2.ORIGIN) AS table_all

在没有最后2列比较的情况下运行相同的查询时,返回4600条记录。

(SELECT CAR_1.ID FROM CAR_1, CAR_2 WHERE 
CAR_1.ID = CAR_2.ID AND 
CAR_1.MODEL = CAR_2.MODEL AND
CAR_1.SYMBOL = CAR_2.SYMBOL ) AS table_min

我想获取其制作和来源不同的47条记录,所以我尝试了下面的sql,但它似乎没有正常工作

select * from (SELECT CAR_1.ID FROM CAR_1, CAR_2 WHERE 
CAR_1.ID = CAR_2.ID AND 
CAR_1.MODEL = CAR_2.MODEL AND
CAR_1.SYMBOL = CAR_2.SYMBOL AND
CAR_1.MAKE = CAR_2.MAKE AND
CAR_1.ORIGIN = CAR_2.ORIGIN) AS table_all
WHERE NOT EXISTS(
(SELECT CAR_1.ID FROM CAR_1, CAR_2 WHERE 
CAR_1.ID = CAR_2.ID AND 
CAR_1.MODEL = CAR_2.MODEL AND
CAR_1.SYMBOL = CAR_2.SYMBOL ) AS table_min
WHERE table_all.ID = table_min.ID 
)

如果有人能告诉我错误,我将不胜感激

2 个答案:

答案 0 :(得分:1)

不是那么简单:

SELECT 
  CAR_1.ID 
FROM 
  CAR_1, CAR_2 
WHERE 
  CAR_1.ID = CAR_2.ID AND 
  CAR_1.MODEL = CAR_2.MODEL AND
  CAR_1.SYMBOL = CAR_2.SYMBOL AND 
  (CAR_1.MAKE <> CAR_2.MAKE OR CAR_1.ORIGIN <> CAR_2.ORIGIN);

答案 1 :(得分:1)

SELECT CAR_1.ID FROM CAR_1
outer join CAR_2 On 
CAR_1.ID = CAR_2.ID 
AND  CAR_1.MODEL = CAR_2.MODEL 
AND CAR_1.SYMBOL = CAR_2.SYMBOL 
AND CAR_1.MAKE = CAR_2.MAKE 
AND CAR_1.ORIGIN = CAR_2.ORIGIN
Where Car2.id is null

将为您提供car1中所有车辆的ID,而Car2中没有匹配的记录

比存在更有效,或者不在子查询中。