我有一个餐桌产品:
ProductID ProductCode SupplierID
1 WATCH 1
2 WATCH 5
我想按产品代码分组:
SELECT ProductID, ProductCode, SupplierID
FROM products
GROUP BY ProductCode
ORDER BY SupplierID DESC
我想显示最后一个 5 的供应商ID,没有条件,没有加入,没有限制为1。
类似下面的输出。
ProductID ProductCode SupplierID
2 WATCH 5
这可能吗?
谢谢!
修改
**Answered by Devon which is called as Noncorrelated Subquery**
SELECT ProductID, ProductCode, SupplierID
FROM products
WHERE SupplierID = (SELECT SupplierID FROM products ORDER BY SupplierID DESC LIMIT 1)
GROUP BY ProductCode
ORDER BY SupplierID DESC
答案 0 :(得分:1)
使用PDO,您可以在查询上运行fetch()以获取第一行。或者你可以为mysqli api运行mysqli_fetch_array(),但是如果你只是试图获得一行,我就不明白你为什么不想使用限制。
$stmt = $pdo->query('..');
$firstrow = $stmt->fetch();
从上一个供应商处获取产品代码的SQL查询:
SELECT ProductID, ProductCode FROM products WHERE SupplierID = (SELECT SupplierID FROM products ORDER BY SupplierID DESC LIMIT 1)
答案 1 :(得分:0)
SELECT ProductID, ProductCode, MAX(SupplierID)
FROM products
GROUP BY ProductCode
注意:强> ProductID列值将是模糊的,即可以是1或2
答案 2 :(得分:0)
是可能的,对supplierID字段使用max()函数,然后按ProductCode进行分组。
由于