Return mysql rows depending on the criteria - mysql

I have a table called payment plan which has this different fields.
I wrote a query to get this rows but I need to modify the query in a way that when I give it a criteria that the amount is 80, which comes from a input field in the html it will only show me one field, from the table, if a I write the amount is 90 it still should show me one table but if I write the amount is 160 or 160 + it should show me both the table. This amounts are basically the CAPITAL_PAYMENT of the table. But I am not sure how to write the query. I wrote this
SELECT c.* , a.Interest
FROM investment a
inner join money_offer b
on a.ORIG_ID = b.investment_orig_id and b.UPDATE_DT is null
inner join payment_plan c
on c.offer_orig_id = b.ORIG_ID and c.UPDATE_DT is null
WHERE a.ORIG_ID = 21 and
a.Owner = 533 and
a.UPDATE_DT is null;
Now I get two rows but depending on amount, if 90, I should get 1 row but I am not sure where do I write it or how.
This amount is basically coming from codeigniter function if it helps here is the code.
public function getLoansBorrowedData($id, $orig_id , $amount){
$query = 'SELECT c.* , a.Interest , d.symbol
FROM investment a
inner join money_offer b
on a.ORIG_ID = b.investment_orig_id and b.UPDATE_DT is null
inner join payment_plan c
on c.offer_orig_id = b.ORIG_ID and c.UPDATE_DT is null
inner join currency d
on c.currency = d.ID
WHERE a.ORIG_ID = '.$orig_id.' and
a.Owner = '.$id.' and
a.UPDATE_DT is null' ;
$query = $this->db->query($query);
/* Return either found rows or false. */
if($query->num_rows() > 0){
$result = $query->result();
return $result;
}
else {
return false;
}
}

Related

A mySQL query to check one option, and if not true, another option?

I am very new at mySQL.
I am doing a lookup of certain records from a table and the requirements have now changed. At first the query would pull the name of the person who was marked as the captain on the job plus a few other conditions. Now my boss wants me to pull the transcriber on the job if there is no captain. How can I do this in mySQL?
My code is:
$Q = $this->read_db->query('
select DISTINCT j.id, j.reference, max(ja.FinalDue) as FinalDue, j.clientdue, j.pagecount, t.name, ja.iscaptain
from `job` j
join `jobattachment` a on a.`jobid` = j.`id`
join `jobassignment` ja on a.`jobid` = ja.`jobid`
join `transcriber` t on ja.`transcriberid` = t.`id`
where ja.`iscaptain` = 1
and ja.`deleted` != 1
and (a.`editing` = 2 or a.`editing` = 3)
and a.`redline` != 0
and j.`complete` = 0
group by j.id');
return $Q->result_array();
How can I make the query find the captain, and only if there is no captain, find the person whose ID is in the redline field? The jobattachment table has multiple records for each job and if the attachment is marked as a redline, the transcriber's ID would be in that field, otherwise it would be empty.
I tried changing the query by adding an or, but I don't want the captain or the transcriber, only the transcriber if there is no captain. Any help would be much appreciated.
I played around with this a lot and this is the solution I have come up with. Thank you to everyone that responded.
public function getRedlinesNotCompleted() {
$Q = $this->read_db->query('
select j.id, j.reference, max(ja.FinalDue) as FinalDue, j.clientdue, j.pagecount, t.name, max(ja.iscaptain) as iscaptain
from `job` j
join `jobattachment` a on a.`jobid` = j.`id`
join `jobassignment` ja on a.`jobid` = ja.`jobid`
join `transcriber` t on ja.`transcriberid` = t.`id`
where ja.`deleted` != 1
and (a.`editing` = 2 or a.`editing` = 3)
and a.`redline` != 0
and j.`complete` = 0
group by j.id');
return $Q->result_array();
}
public function getCaptainNameForRedlineJobsNotCompleted($jobid) {
$Q = $this->read_db->query('
SELECT t.name, max(j.iscaptain) as iscaptain
FROM jobassignment j
JOIN transcriber t ON t.id = j.transcriberid
WHERE j.jobid = ' . $jobid . ' AND j.iscaptain = 1');
return $Q->row()->name;
}
select DISTINCT j.id, j.reference, max(ja.FinalDue) as FinalDue, j.clientdue, j.pagecount, case when ja.iscaptain then t.name else (select name from t where id = a.redline) end , ja.iscaptain
from `job` j
join `jobattachment` a on a.`jobid` = j.`id`
join `jobassignment` ja on a.`jobid` = ja.`jobid`
join `transcriber` t on ja.`transcriberid` = t.`id`
where
and ja.`deleted` != 1
and (a.`editing` = 2 or a.`editing` = 3)
and a.`redline` != 0
and j.`complete` = 0
group by j.id'
Explanation:
First remove the ja.iscaptain = 1 part from the where clause so you can get all the people that also not captains.
Second, the t.name is changed according to the person if he is a captain or not, so instead of returning it hardcoded, you should check if its a captain then its name is t.name, else get the name from transcriber table by a.redline id.
I hope that I understood it correctly and it helps :)

SQL Query based on multiple where conditions

I've got a script where checked in employee's can see the stock inventory from each other, linked with their personal stock location, so each checked in employee can see which items are in stock at different locations. However, I want the main stock (id of 1, which is not attached to an employee) to be showed always, but I can't get the query right because one of the where statements is clearly not correct:
`stock_locations`.`location_id` = 1 AND
`workschedule`.`checkedIn` = 1 AND
Rememeber, the main stock is not linked to an employee, so it doesn't show up at the workschedule table. If I remove the first statement, It clearly shows up all the checked in employee's with their location, but that doesn't give me the main stock. If I remove the second statement, it only shows me the main stock.
How can I solve this issue within SQL? This is btw the full statement:
SELECT
`item_quantities`.`item_id`,
`stock_locations`.`location_name`,
`item_quantities`.`quantity`,
`people`.`first_name`
FROM
`item_quantities`
JOIN `stock_locations` ON `item_quantities`.`location_id` = `stock_locations`.`location_id`
JOIN `items` ON `item_quantities`.`item_id` = `items`.`item_id`
LEFT JOIN `workschedule` ON `workschedule`.`linked_storage` = `stock_locations`.`location_id`
LEFT JOIN `people` ON `workschedule`.`employee_id` = `people`.`person_id`
WHERE
`stock_locations`.`location_id` = 1 AND
`workschedule`.`checkedIn` = 0 AND
`items`.`unit_price` != 0 AND
`items`.`deleted` = 0 AND
`stock_locations`.`deleted` = 0 NULL
Thanks in advance!
Make it an OR statement inside of parens.
(`stock_locations`.`location_id` = 1 OR `workschedule`.`checkedIn` = 1) AND
This will return all records that match either the main stock or the employee.
You need to use the OR operator. Clearly both things can't happen at the same time, so you need to specify each set of acceptable conditions.
SELECT
`item_quantities`.`item_id`,
`stock_locations`.`location_name`,
`item_quantities`.`quantity`,
`people`.`first_name`
FROM
`item_quantities`
JOIN `stock_locations`
ON `item_quantities`.`location_id` = `stock_locations`.`location_id`
JOIN `items`
ON `item_quantities`.`item_id` = `items`.`item_id`
LEFT JOIN `workschedule`
ON `workschedule`.`linked_storage` = `stock_locations`.`location_id`
LEFT JOIN `people`
ON `workschedule`.`employee_id` = `people`.`person_id`
WHERE
`stock_locations`.`location_id` = 1
OR (
AND `workschedule`.`checkedIn` = 1
AND `items`.`unit_price` != 0
AND `items`.`deleted` = 0
AND `stock_locations`.`deleted` = 0
NULL
)
You have LEFT JOIN, but your WHERE clause turns them into inner joins. Fixing that will probably fix your problem:
SELECT . . .
FROM item_quantities iq JOIN
stock_locations sl
ON iq.`location_id` = sl.`location_id` JOIN
items i
ON iq.`item_id` = i.`item_id` LEFT JOIN
workschedule ws
ON ws.`linked_storage` = sl.`location_id` AND
ws.`checkedIn` = 0 LEFT JOIN
--------^
people p
ON ws.`employee_id` = p.`person_id`
WHERE sl.`location_id` = 1 AND
i.`unit_price` != 0 AND
i.`deleted` = 0 AND
sl.`deleted` = 0

i'm using 2 queries is there any way to make it single query

here is my situation,
i'm obtaining id from superadmin table where role=2
like this
SELECT id FROM superadmin WHERE role='2'
suppose i will get 10 records
id
----------------
3
4
6
8
10
14
16
.
.
i need to pass them into 2nd table like this
SELECT status FROM categorydata WHERE users='id' // above id on each iteration
here is my code in PHP:
$query_super_admin = $obj->queryAll("SELECT id FROM superadmin WHERE role='2'");
foreach($query_super_admin['results'] as $result){
$user_id = $result['id'];
$category_related = $obj->queryAll("SELECT status FROM categorydata WHERE users='".$user_id."'");
// result data
}
QUESTION: i want to achieve this with sql is this possible?
TRY THIS : I think INNER JOIN will perform better in this case
SELECT c.status
from superadmin s
inner join categorydata c on s.id = c.users
where s.role='2'
The following query will retrieve users along with their statuses:
SELECT s.id, c.status
FROM superadmin s
LEFT JOIN categorydata c ON s.id = c.users
WHERE s.role = 2
ORDER BY s.id;
I use a LEFT JOIN instead of an INNER JOIN like Suraz because you may be interested in getting users with no status associated.
Then in PHP, to get the same behavior as your initial code, you can do as follows:
$query = <<<EOQ
SELECT s.id, c.status
FROM superadmin s
LEFT JOIN categorydata c ON s.id = c.users
WHERE s.role = 2
ORDER BY s.id;
EOQ;
$query_super_admin = $obj->queryAll($query);
$cur_id = -1;
foreach($query_super_admin['results'] as $result) {
if ($result['id'] != $cur_id) {
// This is a new user id
// Do whatever you want here, like printing user id, name, etc.
$cur_id = $result['id'];
}
if (!$result['status']) {
continue; // No status associated to this user
}
// Do whatever you want here, like printing status
}
You can use WHERE IN (...):
SELECT status
FROM categorydata
WHERE users IN (SELECT id FROM superadmin WHERE role = '2')

Count if a user has reached the borrwing limit

I've setup a fiddle with tables and data here
I'm trying to write a single sql to check if user has reached the borrowing limit for each category.
Right now, it's done using severals sql statements called after each other.
But the way it goes is simple.
memId and id come through a querystring.
$medId = $_POST['memId']; Using 1 for this example. This is the members Id.
$id = $_POST['id']; Using 4 for this example. This is the item being lent.
After that I do:
select id, holder from collection_db where id = 4 // We have a valid item
select borrowMax from collection_db where id = (holder from the previous select) and category = 10 //Result = 2. Category indicates its a label and not a borrowable item.
select count(borrowedId) from lendings where memId = 1 and holder = (holder from the 1st query) //He's borrowed 2, under 1, so cant borrow any more. User 2 may borrow however.
if (count => borrowMax) {echo 'Cannot borrow more.';} else {echo 'Added to'}
How can this be combined into a single sql or is it best left this way?
This seems to produce a correct result set:
SELECT col1.id, col1.holder, col2.borrowMax, count(lend.borrowedId) as `count`
FROM collection_db col1
INNER JOIN collection_db col2
ON col1.holder = col2.id
INNER JOIN lendings lend
ON col1.holder = lend.holder
WHERE col1.id = $id
AND col2.category = 10
AND lend.memId = $medId
I think this combines the queries:
select max(c.borrowMax) as BorrowMax, COUNT(*)
from collection_db c join
collection_db c1
on c.id = c1.holder and c1.id = 4 and c.category = 10 join
lendings l
on l.holder = c1.holder;
It does make an assumption that the join between c and c1 does not produce duplicate rows. But you have this requirement by using = in the original query (rather than join).

Formatting mysql query output

In my query I want to check if the users with the specified permissions exists or not. Presently I am using the below query. It will retrieve the rows of authorised users with the specified conditions.
select a.ixUserAuthorization from tblechecklistuserroleassignmentxref r
inner join tblechecklistuserrole u on u.ixUserRole=r.ixUserRole and u.sname='Initiator'
inner join tblechecklistuserauthorization a on a.ixUserAuthorization=r.ixUserAuthorization
and a.ixcustomer='1'and a.ixprogram='1'and a.ixworkpackage='1'and a.ixactivity='1' and a.ixUser='626e28e8-e67a-4d11-8d2c-129d0ab79e96';
If any rows are returned i want to display the result as true ,If no rows are returned from the above query I want to display the result as false.
How can I modify to obtain the result as true or false .
SELECT CASE
WHEN Count(*) >= 1 THEN 'true'
ELSE 'false'
END AS Answer
FROM (SELECT a.ixUserAuthorization
FROM tblechecklistuserroleassignmentxref r
INNER JOIN tblechecklistuserrole u
ON u.ixUserRole = r.ixUserRole
AND u.sname = 'Initiator'
INNER JOIN tblechecklistuserauthorization a
ON a.ixUserAuthorization = r.ixUserAuthorization
AND a.ixcustomer = '1'
AND a.ixprogram = '1'
AND a.ixworkpackage = '1'
AND a.ixactivity = '1'
AND a.ixUser = '626e28e8-e67a-4d11-8d2c-129d0ab79e96') a
use function mysql_num_rows
ex:
if(mysql_num_rows($result))
echo "true";
else
echo "false";
where $result is the result of your query