claimId是外键
Table (statusTable)
Id_ _chaseStatus_ _claimId_
1 Open CL001
2 Close CL002
3 Open CL001
4 Open CL003
5 Open CL001
6 Open CL003
$query = "SELECT * FROM statusTable ";
$query .= "WHERE (`chaseStatus` = 'Open') ";
$query .= "AND (id = (SELECT MAX(id) FROM statusTable))";
while($row = mysqli_fetch_assoc($result)){
$items[] = $row;
}
//$items = array_reverse($items ,true);
foreach($items as $item){
$claimId = $item["claimId"];
echo $claimId;
}
我的查询只给了我一个最高id的列。
但是我想要只打开'打开'来自' chaseStatus'对于每个'claim'd' (具有最高id);
我怎样才能得到这样的
表示id = 5:CL001
和
表示id = 6:CL003
有什么想法吗?
答案 0 :(得分:4)
您可以使用group by检索claimid的最高ID。
$query = "SELECT max(Id) as Id,claimId FROM statusTable ";
$query .= "WHERE (`chaseStatus` = 'Open') ";
$query .= "GROUP BY claimId";
这应该产生下表
Id claimId
5 CL001
6 CL003
这是一个SQL小提琴:http://sqlfiddle.com/#!2/b000e/1
答案 1 :(得分:0)
您可以通过在子查询中包含'Open'
条件来执行您想要的操作:
SELECT *
FROM statusTable
WHERE `chaseStatus` = 'Open' AND
id IN (SELECT MAX(id) FROM statusTable WHERE chaseStatus = 'Open' GROUP By ClaimId);
我认为在外部查询中使用open
条件是多余的,所以这应该对你有用:
SELECT *
FROM statusTable
WHERE id IN (SELECT MAX(id) FROM statusTable WHERE chaseStatus = 'Open' GROUP BY ClaimId);