MYSQL - Select multiple rows in one query - php

claimId is foreign key
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;
}
My query gives me only one column which is highest id.
But I am trying to get only 'Open' from 'chaseStatus' for each 'claimId' (with highest id) like;
How can I get like this
for id = 5 : CL001
AND
for id = 6 : CL003
Any ideas?

You can retrieve the highest id of the claimid using group by.
$query = "SELECT max(Id) as Id,claimId FROM statusTable ";
$query .= "WHERE (`chaseStatus` = 'Open') ";
$query .= "GROUP BY claimId";
THis should result in the following table
Id claimId
5 CL001
6 CL003
Here's a SQL Fiddle: http://sqlfiddle.com/#!2/b000e/1

You can do what you want by including the 'Open' condition in the subquery:
SELECT *
FROM statusTable
WHERE `chaseStatus` = 'Open' AND
id IN (SELECT MAX(id) FROM statusTable WHERE chaseStatus = 'Open' GROUP By ClaimId);
I think it is redundant to have the open condition in the outer query, so this should work for you:
SELECT *
FROM statusTable
WHERE id IN (SELECT MAX(id) FROM statusTable WHERE chaseStatus = 'Open' GROUP BY ClaimId);

Related

get records between from a start to end number [duplicate]

This question already has answers here:
PHP & MySQL Pagination
(4 answers)
Closed 4 years ago.
This SQL return all records as (JSON) from 2 tables "posts_main" and "posts_comments" that depends on specific User
$sql = "select posts_main.*,
(select groupid from posts_comments where groupid = posts_main.id group by groupid ) as count_comments
from posts_main
WHERE posts_main.user_id = '$user_id' ";
$obj = json_decode($_GET["x"], false);
$stmt = $con->prepare($sql);
$stmt->bind_param("ss", $obj->table, $obj->limit);
$stmt->execute();
$result = $stmt->get_result();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
My Question:
how can I get the first 10 records, then the next 10 records, to the end?
For example:
I'll send "start" = 0, I'll get the first 10 records.
Next time I'll send: "start" = 10, then I'll get the records FROM 10 TO 20.
and so on.
Thank you...
If you have a "start" number, you can frame your query like this -
$sql = "select posts_main.*,
(select groupid from posts_comments where groupid = posts_main.id group by groupid ) as count_comments
from posts_main
WHERE posts_main.user_id = '$user_id' limit 10,10";
MySQL reads 10 records starting at the 11th record in the table.
If you are looking for a Prev, Next solution then PHP pagination is the only option.
Hope this helps you:
$start = 0;
$sql = "select posts_main.*,
(select groupid from posts_comments where groupid = posts_main.id group by groupid ) as count_comments
from posts_main
WHERE posts_main.user_id = '$user_id'
limit '$start' 10";

MySQL query to check mutual values

I have a MySQL DB that resembles the following:
uid suid
1 5
1 6
2 5
5 1
5 2
I am giving it a single unique "uid" via the POST method, call it 1. What I need to do is return all "suid" where $uid "has" suid AND suid (as uid) "has" $uid (as suid.) So, in the above example, the script should only return 5.
I know my first step is
"Select * FROM table Where uid = $uid"
then maybe I have to loop through the results and query the DB WHERE suid = $uid.
I do not know how to do the second query. Any suggestions?
One option here would be to self join, with the join condition being that uid in one table matches suid in the other table, and vice-versa for the suid in the first table.
SELECT
t1.suid
FROM yourTable t1
INNER JOIN yourTable t2
ON t1.uid = t2.suid AND
t1.suid = t2.uid
WHERE
t1.uid = 1
Before applying the WHERE clause, the above query would return two records:
uid | suid (uid not selected)
1 | 5
5 | 1
The WHERE clause then chooses the first record, which is what we want, using the uid parameter which you pass it.
Demo here:
Rextester
this is what I came up with:
$uid = $_POST["UID"];
$myquery = "SELECT * FROM Table WHERE uid = '$uid'";
$result = $conn->query($myquery);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$myquery2 = "SELECT * FROM Table WHERE uid = '" . $row['suid'] . "' AND suid = '$uid'";
$result2 = $conn->query($myquery2);
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
echo $row["uid"].
"!##$";
}
}
}
}
$conn->close();
?>
I feel it is not pretty but it did the trick.

From PHP how to efficiently execute this search in SQL Server?

I have a database structure something like the following:
Table A: PersonId, GroupId
Table B: GroupId, ParentGroupId
Given a PersonId, I want to find the Ids of all people in parent groups of that person's group.
First I select the ParentGroupId for the given PersonId, by joining with B. Then I do a while loop, selecting and recording the PersonId from A based on the GroupId returned in the previous search, and continue the loop by obtaining the next ParentGroupId from B.
Is this an efficient way to do this search, or is there an option that does not involve a while to "bubble up" in this manner?
(this is a simplified version of the actual scenario, changing the schema is not an option)
$sql = 'SELECT ParentGroupID FROM A WHERE PersonId = ' . $id;
$result = $db->query($sql);
$row = $db->fetch_array($result);
$parent_group = $row['ParentGroupId'];
if(!is_null($parent_group)) {
$parent_ids = array();
while($parent_group > 0) {
//is there a way to do this where I retrieve all managers <= lvl 6 at once, so I don't have to loop in order to 'tier up'?
$sql = 'SELECT ParentGroupID, PersonID
FROM B
INNER JOIN A on ParentGroupID = A.GroupID
WHERE ParentGroupID = ' . $parent_group;
$result = $db->query($sql);
$row = $db->fetch_array($result);
$parent_group = $row['ParentGroupID'];
$parent_ids[] = $row['PersonID'];
}
}
Combining your two queries into one would be more efficient:
$sql = 'SELECT ParentGroupID, PersonID
FROM B
INNER JOIN A on ParentGroupID = A.GroupID
WHERE ParentGroupID IN (
SELECT ParentGroupID FROM A WHERE ParentGroupID > 0
AND PersonId = ' . $id .')' ;

how to create the sql_query

I have created some filters in php.3 of them are aimming 1 table. The 4th is aimming another table.
first table is :
id_of_orders :
id_order(int) time(NOW) username(varchar) price(decimal)
the second one is :
order :
order_id(int) product(varchar) price (decimal)
order.order_id is refered to the id_of_orders.id_order
Table id_of_orders is like a mapper to the orders table (id_of_orders.id_order has unique numbers).
Table orders contains many orders some of them have same order_id
I want to return the id_of_orders.id_order which contain the order.product=='proion'
The query that i use is this:
$query = "SELECT * FROM id_of_orders WHERE 1=1";
if(!empty($_SESSION['employees']))
$query .= " AND id_of_orders.username='$_SESSION[employees]'";
if(!empty($_SESSION['timis']))
$query .= " AND id_of_orders.price='$_SESSION[timis]'";
if(!empty($_SESSION['dates']))
$query .= " AND DATE(time)='$_SESSION[dates]'";
//if(!empty($_SESSION['proions']))
// $query .= " AND (orders.product='$_SESSION[proions]' && id_of_orders.id_order==orders.order_id)";
$result = mysql_query($query);
You can try a query like
SELECT o.*
FROM id_of_orders i JOIN
(
SELECT order_id
FROM orders
WHERE product = 'proion'
GROUP BY order_id
) q ON i.id_order = q.order_id
WHERE o.username = ?
AND o.price = ?
AND DATE(time) = ?
or
SELECT i.id_order, i.time, i.username, i.price
FROM id_of_orders i JOIN orders o
ON i.id_order = o.order_id
WHERE 1 = 1
AND o.product = 'proion'
AND o.username = ?
AND o.price = ?
AND DATE(time) = ?
GROUP BY i.id_order, i.time, i.username, i.price

Joining two tables to get a count

I am attempting to count comments on a particular page with the following problematic sql query:
$query = "SELECT * FROM `comments` WHERE is_approved = '1' AND page_id = '943'"
$query = mysql_query($query);
$total = mysql_num_rows($query);
echo $total;
the problem is it is outputting 0 and not 2.
The tables are as follows:
pages:
id:1 page_id:943
id:2 page_id:978
id:3 page_id:977
comments:
id:2 page_id:1 "hello"
id:3 page_id:1 "great"
id:4 page_id:3 "super"
So really the original query should be getting each comment's true page_id from the page_id as set in the pages tables, as joined by comments.page_id = pages.id
What would the final code look like to either make that join, and/or get that count? Thank you.
Try:
SELECT c.* FROM `comments` c
JOIN `pages` p on c.page_id = p.id
WHERE c.is_approved = '1' AND p.page_id = '943'
"SELECT * FROM comments, pages WHERE comments.page_id = pages.id AND is_approved = '1' AND comments.page_id = '943'"
Try using:
SELECT count(*) as cnt
FROM `comments` c join pages p on c.page_id = p.id
WHERE c.is_approved = '1' AND p.page_id = '943'
It seems like a very poor database design to have two columns with the same name in different tables that mean different things. You should probably change the name of pages.page_id to something else.
And, this returns the count directly, so you can read the value from the row. If you just want the count, there is no reason to return all the matching rows.
no join is needed:
$query = "SELECT * FROM `comments` WHERE is_approved = '1' AND WHERE page_id IN (SELECT id WHERE page_id = '943')"
$query = mysql_query($query);
$total = mysql_num_rows($query);
echo $total;
ofcourse i would suggest a count statement if you do not need/use the data:
$query = "SELECT COUNT(*) as total FROM `comments` WHERE is_approved = '1' AND WHERE page_id IN (SELECT id WHERE page_id = '943')"
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$total = $row['total'];
echo $total;

Categories