我正在尝试编写一个查询,从日期比指定日期更新的给定listNumber
中为每companyId
提取searchId
的最低数量。因此,对于每个公司,我会得到一行,其中包含该公司所有条目中listNumber
的最低companyId
行的数据。
(简化的)MySQL表是这样的:
id (PK) companyId (int) searchId (int) productName (varchar) effective (decimal) listNumber (int) addedWhen (timestamp)
searchId
和SELECT MIN(listNumber) AS listnumber, bankId, productName, effective
FROM DummyTableName
WHERE addedWhen >= '2011-04-05 00:00:00'
AND searchId='26'
GROUP BY companyId
与其他两个表格的PK相关联。
我尝试过像
这样的东西listNumber
但没有运气,因为这将返回最低companyId
,但所有其他数据将从具有相同{{1}}的另一行中获取。
关于如何正确获取此查询的任何想法?
答案 0 :(得分:1)
SELECT t1.* FROM table t1
JOIN (SELECT companyId, MIN(listNumber) min_listNumber FROM table
WHERE addedWhen >= '2011-04-05 00:00:00' AND searchId='26'
GROUP BY companyId) t2
ON t1.companyId = t2.companyId AND t1.listnumber = t2.min_listnumber
WHERE t1.addedWhen >= '2011-04-05 00:00:00' AND t1.searchId='26';
答案 1 :(得分:0)
... HAVING Something = MIN(Something)
答案 2 :(得分:0)
你可以尝试
select listnumber,bankid,productname, effective
from dummytablename
left join (SELECT MIN(listNumber) AS listnumber, bankId
FROM DummyTableName
WHERE addedWhen >= '2011-04-05 00:00:00'
AND searchId='26' group by bankid) as t where dummytablename.listnumber=t.listnumber and dummytablename.bankid=t.bankid
但它有点难看(我确定我使用了比这更好的解决方案)
答案 3 :(得分:0)
如果除了聚合函数字段以外的所有内容进行分组,它应该可以工作。在这种情况下,如果你得到一个字段的计数或总和并希望显示该计数/总和,你应该只需要HAVING。
SELECT MIN(listNumber) AS listnumber, bankId, productName, effective
FROM DummyTableName
WHERE addedWhen >= '2011-04-05 00:00:00'
AND searchId='26'
GROUP BY bankId, productName, effective