我的MySQL SELECT查询返回相同行的倍数

时间:2016-04-29 12:19:16

标签: php mysql mysqli rows

由于某些原因,我只能找到一个我能看到的重复行,但无法确定查询中哪些地方出错了。

$stmt = $mysqli->query("
    SELECT DISTINCT vendors_tbl.email AS email,
    (vendor_avails_tbl.standard_pricing - vendor_loc_tbl.offpeak_time_pricing) AS best_margins,
    vendor_loc_tbl.location_id AS locationID,
    vendor_loc_tbl.loc_img_path AS locImg, 
    vendor_loc_tbl.offpeak_time_pricing AS offpeak,
    vendor_loc_tbl.address1 AS address1,
    vendor_loc_tbl.address2 AS address2,
    vendor_loc_tbl.zip_code AS zip,
    vendor_loc_tbl.geocodes AS geo,
    vendor_loc_tbl.has_valet AS valet,
    vendor_loc_tbl.has_transport AS transport,
    vendor_loc_tbl.has_wheelchair AS wheelchair,
    vendor_loc_tbl.has_desk AS desk,
    vendor_loc_tbl.has_24hours AS open24hrs,
    vendor_loc_tbl.has_covered AS covered,
    vendor_loc_tbl.has_security AS security, 
    (vendor_avails_tbl.available_economy + vendor_avails_tbl.available_standard + vendor_avails_tbl.available_midsize + vendor_avails_tbl.available_truck_suv) AS avail_total, 
    vendor_avails_tbl.standard_pricing AS standard_pricing, 69 *
    DEGREES(ACOS(COS(RADIANS($e_lat))
         * COS(RADIANS(SUBSTR(vendor_loc_tbl.geocodes, 1, 10)))
         * COS(RADIANS($e_lon) - RADIANS(SUBSTR(vendor_loc_tbl.geocodes, 13)))
         + SIN(RADIANS($e_lat))
         * SIN(RADIANS(SUBSTR(vendor_loc_tbl.geocodes, 1, 10))))) AS distance_in_m
    FROM vendors_tbl
    INNER JOIN vendor_loc_tbl ON vendor_loc_tbl.vendor_id = vendors_tbl.vendor_id
    INNER JOIN vendor_avails_tbl ON vendor_avails_tbl.location_id = vendor_loc_tbl.location_id
    WHERE vendor_avails_tbl.available_standard > 0
    ORDER BY vendor_loc_tbl.override_level DESC, best_margins DESC, distance_in_m ASC
    LIMIT 5
");

2 个答案:

答案 0 :(得分:1)

嗯,在某些情况下,使用GROUP BY语句而不是DISTINCT的下注者。在您的示例中,您应该至少在一个col上添加一个组(一些唯一的例如id)。当您在查询中使用聚合时,最好使用group by,当仅使用连接时 - distinct足够了。

答案 1 :(得分:0)

您的distinct会创建您指定的所有字段的组,因为您没有按条件指定组。 所以没有机会获得重复的价值。