我正在使用以下查询从mysql数据库中提取信息,虽然我得到min(qt.quote_price)的正确值,但我得到了st.Supplier_id的错误值。
它似乎从满足where子句的表返回第一个st.Supplier_id,但显然我希望它以min(qt.quote_price)返回行的st.Supplier_id。
我确信这很简单,但由于某种原因,我无法理解,希望有人可以指出我正确的方向。
SELECT ft.fuel_type_id, ft.fuel_name, st.Supplier_id, st.company_name as company_name, st.email, qt.supplier_id, qt.timestamp, qt.fuel_type_id, min( qt.quote_price ) AS best_derv
FROM tbl_quote qt
INNER JOIN `tbl_suppliers` st ON qt.supplier_id = st.Supplier_id
INNER JOIN `tbl_fuel-type` ft ON qt.fuel_type_id = ft.fuel_type_id
WHERE qt.fuel_type_id =3 AND qt.timestamp > date_sub( NOW(), INTERVAL 7 DAY )
我已经将查询编辑为有效的内容,但我希望有任何帮助来改进它(如果可能的话)。
SELECT qt.quote_id, ft.fuel_type_id, ft.fuel_name, st.Supplier_id, st.company_name as company_name, st.email, qt.supplier_id, qt.timestamp, qt.fuel_type_id, min( qt.quote_price ) AS best_derv
FROM tbl_quote qt
INNER JOIN `tbl_suppliers` st ON qt.supplier_id = st.Supplier_id
INNER JOIN `tbl_fuel-type` ft ON qt.fuel_type_id = ft.fuel_type_id
WHERE qt.quote_price = (Select min(quote_price) from tbl_quote where fuel_type_id =3 AND timestamp > date_sub( NOW(), INTERVAL 7 DAY ))
答案 0 :(得分:0)
您需要添加一个列出所有非聚合列的GROUP BY
子句:
SELECT ft.fuel_type_id, ft.fuel_name, st.Supplier_id, st.company_name as company_name, st.email, qt.supplier_id, qt.timestamp, qt.fuel_type_id, min( qt.quote_price ) AS best_derv
FROM tbl_quote qt
INNER JOIN `tbl_suppliers` st ON qt.supplier_id = st.Supplier_id
INNER JOIN `tbl_fuel-type` ft ON qt.fuel_type_id = ft.fuel_type_id
WHERE qt.fuel_type_id =3
AND qt.timestamp > date_sub( NOW(), INTERVAL 7 DAY )
GROUP BY ft.fuel_type_id, ft.fuel_name, st.Supplier_id, st.company_name, st.email, qt.supplier_id, qt.timestamp, qt.fuel_type_id
在所有其他(非mysql)数据库中,您将收到描述问题的错误消息,但mysql允许这种情况,在这种情况下,它返回第一行而不是聚合行。