区别在sql中不起作用

时间:2016-03-16 19:29:00

标签: mysql sql inner-join distinct

Select Distinct _Ad.ad_id,_Ad.Ad_Name,ID.Image_Path,VM.year,VD.Vehicle_Transformation,VD.Vehicle_Fuel_Type,VD.Vehicle_Millege
from _Ad 
inner join _Image_Details ID 
on ID.ad_id = _Ad.ad_id
inner join _Vehicle_Model VM
on VM.vehicle_model_id = _AD.vehicle_model_id
inner join _Vehicle_Details VD
on _ad.ad_id=VD.ad_id
inner join _Vehicle_Make VMA
on VM.vehicle_make_id=VMA.vehicle_make_id
where
VMA.Vehicle_Make='' OR
VM.Vehicle_Model='' OR
VD.Vehicle_Fuel_Type='' OR
VD.Vehicle_Seats='' OR
_Ad.price>'0' OR _Ad.price<'8888888'

我正在使用此查询但显示4条记录不是1.我只需要1条ad_id内的单条记录。请帮助。 enter image description here

1 个答案:

答案 0 :(得分:0)

而不是SELECT DISTINCT,请尝试使用SELECT TOP 1。所以你的代码看起来像

SELECT TOP 1 a.ad_id,
    a.Ad_Name, 
    b.Image_Path, 
    c.year,
    d.Vehicle_Transformation,
    d.Vehicle_Fuel_Type,
    d.Vehicle_Millege
FROM _Ad a, _Image_Details b, 
    _Vehicle_Model c, 
    _Vehicle_Details d, 
    _Vehicle_Make e
WHERE b.ad_id = a.ad_id 
    AND c.vehicle_model_id = a.vehicle_model_id 
    AND a.ad_id = d.ad_id 
    AND c.vehicle_make_id = e.vehicle_make_id
    e.Vehicle_Make='' OR
    c.Vehicle_Model='' OR
    d.Vehicle_Fuel_Type='' OR
    d.Vehicle_Seats='' OR
    a.price>'0' OR a.price<'8888888'

如果你想要每个a.ad_id中的一个,你需要摆脱b.Image_Path。所以它看起来像这样:

SELECT DISTINCT a.ad_id,
        a.Ad_Name, 
        c.year,
        d.Vehicle_Transformation,
        d.Vehicle_Fuel_Type,
        d.Vehicle_Millege
    FROM _Ad a, _Image_Details b, 
        _Vehicle_Model c, 
        _Vehicle_Details d, 
        _Vehicle_Make e
    WHERE b.ad_id = a.ad_id 
        AND c.vehicle_model_id = a.vehicle_model_id 
        AND a.ad_id = d.ad_id 
        AND c.vehicle_make_id = e.vehicle_make_id
        e.Vehicle_Make='' OR
        c.Vehicle_Model='' OR
        d.Vehicle_Fuel_Type='' OR
        d.Vehicle_Seats='' OR
        a.price>'0' OR a.price<'8888888'