Summation Query with join codeigniter - php

I have 2 tables. One with a list of clients and another with a list of data. I am trying to create a table in my view that lists the client name along with the sum of a column(job_total) in the data table. I am able to write a query that works fine in most situations. The problem is, if I have not yet created a record in the data table I need to still display the client name with a balance of zero on my table in my view. Need some direction on how to handle this. I was thinking I need to query my list of clients and loop through that query just not sure how to do it.
I want my view to look like below:
+-------------+---------+
| Client Name | Balance |
+-------------+---------+
| xxx | $75.00 |
| xxx | $100.00 |
| xxx | $0.00 |
+-------------+---------+
Here is a rough layout of the two tables in my database:
cj_clients
+----+-------------+
| id | client name |
+----+-------------+
| 1 | client1 |
| 2 | client2 |
| x | xxx |
+----+-------------+
cj_data
+----+-----------+-----------+
| id | client_id | job_total |
+----+-----------+-----------+
| 1 | 1 | 5.00 |
| 2 | 1 | 10.00 |
| 3 | 1 | 15.00 |
+----+-----------+-----------+
The below code returns the desired results except when no entries have yet been made to the cj_data table. Not sure how to still get the client in the table view with a balance of $0.
$this->db->select('client_name,client_id, sum(job_total) AS balance')
->from('cj_data')
->join('cj_clients','cj_data.client_id = cj_clients.id')
->group_by('client_name');
return $this->db->get()->result();

You need to give left join
$this->db->select('client_name,client_id, IFNULL(sum(job_total),0) AS balance')
->from('cj_data')
->join('cj_clients','cj_data.client_id = cj_clients.id',"left") // here
->group_by('client_name');
return $this->db->get()->result();
I wrote IFNULL condition if record not found or it will show all data for all clients in cj_clients
Note: the Default behaviour of CodeIgniter is it will add inner join
if join not specified

Related

Get last inserts from multiple tables

i am trying to build something like an order management tool for a car garage.
The main function of the tool is to manage repair orders and inspection orders as well
Therefore i have created this following three tables.
In the first one you can see the cars and the state of the repair and inspection.
The second one shows the information about the single repair orders the relation between the first and this is 1:n.
The last one shows the automaticly created inspection orders for each car out of the first table. This is an 1:n relation as well.
So what i try to do is to show all the open repair and inspection orders for the cars in one table. But only the open ones.
I tried it with some where statements but i got totaly confused.
My question is, how i can realise it?
+------+--------------------------+----------+------------+
| IDWZ | wz_name | wz_stand | wz_vistand |
+------+--------------------------+----------+------------+
| 1 | Querbr?cke vorn | 0 | 0 |
| 2 | Front Lateral Support | 0 | 1 |
| 3 | Rear Support | 1 | 1 |
| 4 | MID-X-Member Upper Shell | 1 | 1 |
| 5 | Front Lateral Support | 1 | 1 |
+------+--------------------------+----------+------------+
+---------+-----------------+--------------+
| IDWZTBL | rep_wzrepstatus | rep_wzfehler |
+---------+-----------------+--------------+
| 2 | 1 | REP 1 |
| 1 | 1 | REp2 |
| 1 | 1 | REp 3 MASS |
| 1 | 0 | 444 |
| 2 | 0 | |
+---------+-----------------+--------------+
+--------+-------------+
| VIWZID | vi_repstand |
+--------+-------------+
| 1 | 0 |
+--------+-------------+
Sry for that!
So the IDWZ is the foreign KEY in the second table(IDWZTBL) and in the third (VIWZID).
I tried it with
SELECT wz_name, wz_stand, wz_vistand, rep_wzrepstatus, vi_repstand FROM tbl_wz LEFT JOIN tbl_orders ON tbl_wz.IDWZ = tbl_orders.IDWZTBL LEFT JOIN tbl_vi ON tbl_wz.IDWZ = tbl_vi.VIWZID WHERE wz_stand='0' AND rep_wzrepstatus='0' ...
Only for the first table cars to the second one repair orders, that WHERE staement (WHERE wz_stand='0' AND rep_wzrepstatus='0') works fine.
But if i try to add the third table (VI) doing the same, i could fetch the result i wanna have.
What i wanna see in the Overview table is only the last open repair order and the last open inspection order.

Select MySQL return table header as well table body in one query

Hello I am facing hard time trying to realized this task. The problem is that I am not sure in which way this have to be proceeded and couldn't find tutorials or information about realizing this type of task.
The question is I have 2 tables and one connecting table between the two of them. With regular query usually what is displayed is the table header which is known value and them then data. In My case I have to display the table horizontally and vertically since the header value is unknown value.
Here is example of the DB
Clients:
+--------+------ +
| ID | client|
+--------+------ +
| 1 | Sony |
| 2 | Dell |
+--------+------ +
Users:
+--------+---------+------------+
| ID | name | department |
+--------+--------+-------------+
| 1 | John | 1|
| 2 | Dave | 2|
| 3 | Michael| 1|
| 4 | Rich | 3|
+--------+--------+-------------+
Time:
+--------+------+---------------------+------------+
| ID | user | clientid | time | date |
+--------+------+---------------------+------------+
| 1 | 1 | 1 | 01:00:00 | 2017-01-02 |
| 2 | 2 | 2 | 02:00:00 | 2017-01-02 |
| 3 | 1 | 2 | 04:00:00 | 2017-02-02 | -> Result Not Selected since date is different
| 4 | 4 | 1 | 02:00:00 | 2017-01-02 |
| 5 | 1 | 1 | 02:00:00 | 2017-01-02 |
+--------+------+---------------------+------------+
Result Table
+------------+--------+-----------+---------+----------+
| Client | John | Michael | Rich | Dave |
+------------+--------+-----------+---------+----------+
| Sony |3:00:00 | 0 | 2:00:00 | 0 |
+------------+--------+-----------+---------+----------+
| Dell | 0 | 0 | 0 | 2:00:00 |
+------------+--------+-----------+---------+----------+
First table Clients Contains information about clients.
Second table Users Contains information about users
Third Table Time contains rows of time for each users dedicated to different clients from the clients table.
So my goal is to make a SQL Query which will show the Result table. In other words it will select sum of hours which every user have completed for certain client. The number of clients and users is unknown. So first thing that have to be done is Select all users, no matter if they have hours completed or not. After that have to select each client and the sum of hours for each client which was realized for individual user.
The problem is I don't know how to approach this situation. Do I have first to make one query slecting all users then foreach them in the table header and then realize second query selecting the hours and foreaching the body conent, or this can be made with single query which will render the whole table.
The filters for select command are:
WHERE MONTH(`date`) = '$month'
AND YEAR(`date`) ='$year'
AND u.department = '$department'
Selecting single row for tume SUM is:
(SELECT SUM( TIME_TO_SEC( `time` ) ) FROM Time tm
WHERE tm.clientid = c.id AND MONTH(`date`) = '$month' AND YEAR(`date`) ='$year'
This is the query to select the times for a user , here by my logic this might be transformed with GROUP BY c.id (client id), and the problem is that it have to contains another WHERE clause which will specify the USER which is unknown. If the users was known value was for example 5, there is no problem to make 5 subsequent for each user WHERE u.id = 1, 2, 3 etc.
So here are the 2 major problems how to display in same query The users header and them select the sum of hours for each client corresponding the user.
Check out the result table hope to make the things clear.
Any suggestion or answer which can come to resolve this situation will be very helpful.
Thank you!

Mysql join query multiple values

I have a table called facility.
Structure looks as follows:
id | name
---------
1 | Hotel
2 | Hospital
3 | medical shop
I have an other table which is taking data from the above table and keeping multiple values in one column. View looks like below:
id | facilities
---------------
1 | Hospital~~medical shop~~Hotel
2 | Hospital~~Hotel
3 | medical shop~~Hotel
If I want to join these two tables how does the query look like?
I tried this, but it didn't work:
select overview.facilities as facility
from overview join facility on facility.id=overview.facilities;
you can do this with a bit of hackery
select o.facilities as facility
from overview o
join facility f on find_in_set(f.facilities, replace(o.facilities, '~~', ','));
I would highly recommend you change the way you are storing data. currently it is considered un normalized and that quickly becomes a monster to deal with
you should change your table structure to look something more like this
+----------+--------------+
| facility |
+----------+--------------+
| id | name |
+----------+--------------+
| 1 | Hotel |
| 2 | Hospital |
| 3 | medical shop |
+----------+--------------+
+-----------+-------------+
| overview |
+-----------+-------------+
| id | facility_id |
+-----------+-------------+
| 1 | 2 |
| 2 | 3 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 3 |
| 7 | 1 |
+-----------+-------------+
Code Explanation:
basically you are wanting to find the matching facilities in the overview. one handy function MySQL has is FIND_IN_SET() that allows you to find an item in a comma separated string aka find_in_set(25, '11,23,25,26) would return true and that matching row would be returned... you are separating your facilities with the delimiter ~~ which wont work with find_in_set... so I used REPLACE() to change the ~~ to a comma and then used that in the JOIN condition. you can go from here in multiple ways.. for instance lets say you want the facility id's for the overview.. you just add in the select GROUP_CONCAT(f.id) and you have all of the id's... note if you do that you need to add a GROUP BY at the end of your query to tell it how you want the results grouped

Search and print result from multiple queries

I have 3 tables. service_robot_errorservice contains a foreign key that is primary key in the service table. robot_error does not have ore give any foreign keys.
TABLE: robot_error
| id | date | stop_time | start_time | robot | position | error_code | observation | solution | downtime | logged_by |
| 1 | 02.01.2012 | 14:51:31 | 14:52:00 | 20 | 25/7 | 214 | X dir | Rob off | 29 | XXX |
TABLE: service
| service_id | service_date | service_module | service_user | service_comment | service_type |
| 1 | 13.01.2012 | Robot | XXX | Test service | Errorservice |
TABLE: service_robot_errorservice
| errorservice_id | service_id | errorservice_robot | errorservice_tracksensor | errorservice_gripper |
| 5 | 1 | 54 | OK | OK |
When a user searches for a robot (eks 16) i want the result to be every instance in robot_error orderd by date AND if the robot has service registered this instance should also be shown in the result.
Example:
robot_error instance
robot_error instance
robot_error instance
service instance
robot_error instance
service instance
That is what i want the result to look. I've tryed to first get the result out of this SQL
SELECT * FROM robot_error WHERE robot = '16'
and make a while to loop all results in robot_error table but i cant figure out how i can make the result from service tables to be shown, can anyone help? :)
I'd recommend using joins.
JOIN: Return rows when there is at least one match in both tables
LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
FULL JOIN: Return rows when there is a match in one of the tables
But you'd have to have a relation between robot_error and service before you can use a query with a join. It would probably look something like this:
SELECT * FROM robot_error LEFT OUTER JOIN services ON robot_error.ID = services.FK WHERE robot = '16'
Jeff Atwood demonstrates the different Joins quite nicley

PHP: Fetching data from *strange* MySQL database

I have a closed-source software written in C#/.NET from a VoIP company which is impossible to customize and wanted to create custom front-end using PHP. I gained access to the database and now see how it functions. I wanted to output the user his 'speed dial' numbers, but having issue solving it. Here are the tables structures:
'customer' table
+-------------------------------------------------------------------------+
| CustomerID | FirstName | LastName | Balance | Email | Password | Status |
|-------------------------------------------------------------------------|
| 1 | Homer | Simpson | 5.00 | h#s.s | iheartm | 1 |
| 2 | Marge | Simpson | 3.00 | m#s.s | ihearth | 1 |
+-------------------------------------------------------------------------+
'calls' table
+------------------------------------------------------------------------+
| CallID | Caller | Callee | ServiceID | Duration | Cost | CustomerID |
|------------------------------------------------------------------------|
| 1 | 1234567 | 7654321 | 30 | 60 | 1.00 | 1 |
| 2 | 7654321 | 1234567 | 45 | 120 | 2.00 | 2 |
+------------------------------------------------------------------------+
'ani' (speed-dial) table
+---------------------------------------+
| PhoneNumber | ServiceID | ContactName |
|---------------------------------------|
| 1234567 | 45 | Homer |
| 7654321 | 30 | Marge |
+---------------------------------------+
As you can see, 1234567 is Homer's phone number and in Marge's speed dial list and 7654321 is Marge's number in Homer's list. Just like I can pull up customer's balance when logged in using: $current_user['Balance'];, is there way to show user his 'speed dial' numbers in PHP?
This request doesn't achieve what you want ?
SELECT
a.CustomerID, a.FirstName, a.LastName, a.Balance, a.Email, a.Status,
b.ServiceID,
(SELECT GROUP_CONCAT(CONCAT(ContactName,':',PhoneNumber)) FROM ani GROUP BY PhoneNumber WHERE ServiceID = b.ServiceID)
FROM customer a
LEFT JOIN calls b ON a.CustomerID = b.CustomerID
WHERE a.CustomerID = 'replace_by_customer_id'
This should fetch the data of the customer table, plus a string that results from concatenating the speed-dial numbers of the customer connected.
I assume that a customerid corresponds to one unique serviceid found in calls, and the serviceid in the table ani indicates the owner of the speed-dial number. But it seems a weird architecture, so you should give us more data or informations about the tables...
There seems to be a missing relation from ServiceID to a specific entry in customer. It would seem strange that the calls table would provide that relation, it should merely use it.
With only the information you supplied you can only join calls to link the CustomerID with the ServiceID which I suppose you have. The query would look like this:
SELECT ContactName, PhoneNumber FROM ani
LEFT JOIN calls ON ani.ServiceID=calls.ServiceID
WHERE calls.CustomerID=xxx

Categories