添加内部联接会使查询显示重复项

时间:2015-08-03 23:32:17

标签: mysql sql mysqli

显示表的子集

SELECT cont.ID, cont.UUID
FROM  `contract` cont
INNER JOIN geoPoint geo ON geo.cUUID = cont.c_UUID
WHERE geo.geotype =1
AND geo.g_UUID =  '$uuid'

添加其他GT

  SELECT cont.ID, cont.UUID
    FROM  `contract` cont
    INNER JOIN geoPoint geo ON geo.cUUID = cont.c_UUID
    INNER JOIN tier gt ON gt.UUID = cont.price_tier
    WHERE geo.geotype =1
    AND geo.g_UUID =  '$uuid' AND gt.type = 0

现在它显示了数千个重复的项目

4 个答案:

答案 0 :(得分:0)

很有可能你需要更好地解释你在寻找什么以及你的数据如何与你联系以得到一个非猜测的答案,但这是我猜测的......

SELECT cont.ID, cont.UUID
FROM  `contract` cont
WHERE cont.c_UUID IN (
    SELECT geo.cUUID 
    FROM geoPoint AS geo 
    WHERE geo.geotype =1
    AND geo.g_UUID =  '$uuid'
)
AND cont.price_tier IN (
    SELECT gt.UUID 
    FROM tier AS gt
    WHERE gt.type = 0 
)
;

答案 1 :(得分:0)

如果层表每个UUID有多个值(这很奇怪),则需要使用EXISTS子句

SELECT cont.ID, cont.UUID
FROM  `contract` cont
INNER JOIN geoPoint geo ON geo.cUUID = cont.c_UUID
WHERE geo.geotype =1
AND geo.g_UUID =  '$uuid' AND gt.type = 0
AND EXISTS (SELECT * FROM tier gt WHERE gt.UUID = cont.price_tier)

答案 2 :(得分:0)

一种简单的方法来解决返回比预期更多记录的JOIN是查看数据以查看导致它的原因。一次从一个表中取DISTINCT *将向您显示原因,在这种情况下,它显然是tier表,因为这是导致麻烦的添加:

  SELECT DISTINCT gt.*
    FROM  `contract` cont
    INNER JOIN geoPoint geo ON geo.cUUID = cont.c_UUID
    INNER JOIN tier gt ON gt.UUID = cont.price_tier
    WHERE geo.geotype =1
    AND geo.g_UUID =  '$uuid' AND gt.type = 0

观察具有多行的gt.UUID的值,然后您将能够确定最佳行动方案......也许有空白值连接到每一侧的许多记录,也许还有另一个字段您需要添加到JOIN条件...无论如何,观察数据将帮助您确定错误,因为正如您所说,您的查询看起来很好。

答案 3 :(得分:0)

SELECT DISTINCT  cont.ID, cont.UUID

FROM  `contract` cont

INNER JOIN geoPoint geo ON geo.cUUID = cont.c_UUID

INNER JOIN tier gt ON gt.UUID = cont.price_tier

WHERE geo.geotype =1

AND geo.g_UUID =  '$uuid' AND gt.type = 0