我想从两个独立工作的查询或一个可以合并我的两个查询的查询生成单个结果响应。
我的第一个问题是:
$query =" SELECT *
FROM locationdetails
WHERE user_id = " . $userid . " AND trip IN (SELECT DISTINCT trip FROM locationdetails
GROUP BY trip
HAVING _id = max( _id ))
ORDER BY trip DESC
LIMIT 0 , 5";
第二个查询几乎相同:
$query =" SELECT *
FROM locationdetails
WHERE user_id = " . $userid . " AND trip IN (SELECT DISTINCT trip FROM locationdetails)
GROUP BY trip
HAVING _id = min( _id )
ORDER BY trip DESC
LIMIT 0 , 5";
但我需要生成一个响应。需要一些直接的帮助。 我也通过以下方法生成响应:
function ExecuteQuery($query) {
$response = new ApiResult();
if (mysqli_query($this->con, $query)) {
$results_array = array();
$sqlResult = mysqli_query($this->con, $query);
while ($row = $sqlResult->fetch_assoc()) {
$results_array[] = $row;
}
if ($results_array != null || !empty($results_array)) {
$response->Message = 'SUCCESSFULL';
$response->Result = $results_array;
} else {
$response->Message = 'SUCCESSFULL';
// $response->Result = 'N;
}
mysqli_close($this->con);
} else {
$response->Message = 'Some Internal problem occurred';
$response->Error = true;
}
return $response;
}
答案 0 :(得分:1)
如下:
$query =" SELECT trip, MIN(_id) AS minid, MAX(_id) AS maxid
FROM locationdetails
WHERE user_id = " . $userid . "
GROUP BY trip
ORDER BY trip DESC
LIMIT 0 , 5";
这将为您提供每个不同行程的列表,其中包含每个行程的最小和最大ID。
答案 1 :(得分:-1)
如果您想要来自两个查询的唯一记录,请使用UNION 和 如果您想要两个查询中的所有记录,请使用UNION ALL。
(SELECT *
FROM locationdetails
WHERE user_id = " . $userid . " AND trip IN (SELECT DISTINCT trip FROM locationdetails
GROUP BY trip
HAVING _id = max( _id ))
ORDER BY trip DESC
LIMIT 0 , 5
)
UNION
OR
UNION ALL
(SELECT *
FROM locationdetails
WHERE user_id = " . $userid . " AND trip IN (SELECT DISTINCT trip FROM locationdetails)
GROUP BY trip
HAVING _id = min( _id )
ORDER BY trip DESC
LIMIT 0 , 5
)