1

我正在使用以下查询从 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 ))
4

1 回答 1

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 允许这种情况,在这种情况下,它返回第一行而不是聚合行。

于 2013-10-05T20:14:41.153 回答