MySQL加入返回的倍数,应该返回单个

时间:2012-02-22 20:05:26

标签: mysql join union

嘿伙计们,我刚刚注意到我的加入声明

        SELECT *
        FROM reports rpt
        JOIN (
            (SELECT report_key, shipper, po, commodity, label
            FROM berries)
            UNION 
            (SELECT report_key, shipper, po, commodity, label
            FROM melons)
            UNION 
            (SELECT report_key, shipper, po, commodity, label
            FROM citrus)
            UNION 
            (SELECT report_key, shipper, po, commodity, label
            FROM table_grapes)
            UNION 
            (SELECT report_key, shipper, po, commodity, label
            FROM tree_fruit)
            UNION 
            (SELECT report_key, shipper, po, commodity, label
            FROM lot)
        ) fruits ON rpt.inspection_number = fruits.report_key
        WHERE rpt.status < '2' 
        ORDER BY rpt.inspection_number DESC

返回查询符合条件的每一行,我想要的是什么 得到它返回一行,我做错了什么?

2 个答案:

答案 0 :(得分:0)

您可以在末尾添加limit n子句,使其只返回一行:

    SELECT *
    FROM reports rpt
    JOIN (
        (SELECT report_key, shipper, po, commodity, label
        FROM berries)
        UNION 
        (SELECT report_key, shipper, po, commodity, label
        FROM melons)
        UNION 
        (SELECT report_key, shipper, po, commodity, label
        FROM citrus)
        UNION 
        (SELECT report_key, shipper, po, commodity, label
        FROM table_grapes)
        UNION 
        (SELECT report_key, shipper, po, commodity, label
        FROM tree_fruit)
        UNION 
        (SELECT report_key, shipper, po, commodity, label
        FROM lot)
    ) fruits ON rpt.inspection_number = fruits.report_key
    WHERE rpt.status < '2' 
    ORDER BY rpt.inspection_number DESC
    LIMIT 1                                               -- limit !!

这将返回第一行。

答案 1 :(得分:0)

好吧,如果该行的inspection_number与来自任何表berry,melons,citrus,table_grapes,tree_fruit或lot的report_key匹配,则返回状态小于'2'的报告中的所有行。

您期望单排?