Select from 3 joined tables with condition? - mysql

I have four tables:
request:
id----salesid--custid---serial-----active
=======================================
1-------2-------1--------13221-------1
2-------1-------2--------15422-------1
3-------1-------3--------11233-------1
4-------2-------1--------11342-------1
salesid is foreign key from emp table and we don't need any thing from employee table except the emp id so its not important to show its details
custid is foreign key of customer id
serial is the serial of that request
active is flag for delete
requestcondition:
id-----requestid-----requestcondition
======================================
1--------1-------------pending
2--------1-------------installation pending
3--------2-------------pending
4--------1-------------completed
and
customer:
id------name
============
1-------aaaa
2-------bbbb
3-------cccc
I want to select last condition added for specific request and the name of the customer and request serial according to the salesid column

Try
SELECT Id=scope_identity();
Or
LAST_INSERT_ID();
Through this you can get the last inserted Id and after getting last condition, Implement joins.Read about it on this Link.

select r.id, rc.id, c.name, r.serial, rc.requestcondition
from request r
inner join customer c on c.id=r.custid
inner join requestcondition rc on rc.requestid=r.id
inner join (
select max(id) as rcid
from requestcondition
group by requestid
) latest on latest.rcid=rc.id
This will give the latest status of all requests. If you need just the latest status for one request, you would need to add a where clause at the end.

Related

How to get all columns from one table and only one column from another table with ID ? - MySql

I have table employee which contains about 9 columns . ' id,name,etc..'
and I have another table 'onCall' contain 3 columns 'employee_id,department_id and rank '
what I want is to retrieve the employee data who is registered as OnCall employee on this department
I try this to get the employee data :
Select * from employee where id in (SELECT employee_id FROM onCall where department_id = 3)
But like this I can't know what is the rank of the onCall employee , is he registered as primary or backup ,how can I merge rank column from onCall table but only for the selected employee by the id
I tried to join them but I get syntax error
any way to solve this ?
This calls for an inner join
select EMP.*, OC.*
from EMPLOYEE EMP
inner join ONCALL OC
on OC.EMPLOYEE_ID = EMP.ID
where OC.DEPARTMENT = 3
This may help you and use the required columns with table alias name
Select e.*, o.* from employee e
LEFT JOIN onCall o ON o.employee_id = e.id
AND o.department_id = 3

SQL Query from Three Related Tables

I am having trouble putting together a MySQL query.
I have a database with three tables: Location, LocationTypes, and LocationStatus.
I need to retrieve the total of each type of status for each location. So, I the result should look like this:
id_LocationType, status, total
1, open, 200
1, closed, 100
2, open, 400
2, closed, 500
The query should accessing three tables.
LocationTypes --< Locations --< LocationStatus
I came up with this:
SELECT status, COUNT(DISTINCT id_Locations)
FROM LocationStatus
GROUP BY status
But this does not give me the status by LocationType, It gives me the total status for each type of status, combining all LocationTypes:
status, value
open, 600
closed, 600
It doesn't distinguish between LocationType (from the LocationType table). Also, it counts all status values. However, as a location can have multiple status records (ie. a record is created each time the status is updated), I want to count only the most recent status update as the valid one.
The schema looks like this:
Locations Table
-- id (PK)
-- id_LocationType (FK to LocationTypes Table)
-- name
-- date_created
-- date_modified
LocationTypes Table
-- id (PK)
-- nameLocationType
-- date_created
-- date_modified
LocationStatus Table
-- id (PK)
-- id_Location (FK to Location Table)
-- status
-- date_created
-- date_modified
So, it is linked like this:
LocationTypes --< Locations --< LocationStatus
How do I put together this query?
You need to group the result by both LocationType and status. Try this:
SELECT id_LocationType, status, COUNT(DISTINCT id_Locations)
FROM Locations join LocationStatus
ON Locations.id = LocationStatus.id_Location
GROUP BY id_LocationType, status
I hope so this query will be helpful for you.
select lt.id as id_LocationType , ls.status,count(*)
from LocationTypes as lt join Locations as l join LocationStatus as ls
on lt.id=l.id_LocationType and on l.id=ls.id_location
Group by lt.id,ls.status.

Get record in many to many table with null row

I have three tables
1. Employee
2. Calendar
3. Check-in/out
Check-in/out have two foreign key emp_id from Employee and cal_id. Now Problem is how get the record of Employee not in table Check-in/out with date in calendar.
Simply say, get employee Absents record
I think you can use a CROSS JOIN and NOT EXISTS:
SELECT e.*, c.*
FROM Employee e
CROSS JOIN Calendar c
WHERE NOT EXISTS
(
SELECT 1 FROM [Check-in/out] cio
WHERE cio.emp_id = e.emp_id
AND cio.cal_id = c.cal_id
)

SQL COUNT() function and LEFT OUTER JOIN

I have two tables, users and departments. I want to have table, where are two columns: first is department name, second is count - how many users are assigned to this department.
And I have this piece of code:
SELECT department_name as 'deptName',
COUNT(users.department_id) as 'userCount'
FROM departments
LEFT OUTER JOIN users
ON departments.id = users.department_id
GROUP BY 'deptName'
Department's table columns are:
integer id PK
varchar(20) department_name
User's table columns are:
integer id PK
varchar(20) name
varchar(20) surname
int department_id FK
But it does not work.
Now I have 2 departments, and output should be 2 rows, first with count 8 and second with count 1. But I see only one row, with all count (9).
I use MySQL installed with XAMPP.
SELECT department_name as 'deptName',
COUNT(users.department_id) as 'userCount'
FROM departments
LEFT OUTER JOIN users
ON departments.id = users.department_id
GROUP BY `deptName`
Notice the tick marks vs. your single quotes in the GROUP BY (this is the key to the left of the 1 on your keyboard). Refer to: http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html
You could also just group by department_name (the field itself, rather than the alias)
Currently you are grouping on the literal value 'deptName', not the field that you've given an alias of deptName, which is why you only have 1 row returned. You're not actually doing any grouping.

SQL query to retrive data [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
For these relations:
Customer(CID, Name, City, State),
Order(OID, CID, Date), and
Product(PID, ProductName, Price)
LineItem(LID, OID,PID, Number, TotalPrice),
where CID is a customer id and is a key for Customer, OID is an order id and is a key for Order, and LID is a line item id and is a key for LineItem. In addition the attribute CID of Order is a foreign key referring to the CID of Customer, that is, for each CID c of Order there is exactly one tuple of Customer whose CID attribute is c. The OID of LineItem is a foreign key referring to the OID of Order. There are several line items for the same order, a line item refers to a product and contains the quantity ordered for the product.
What is the query for:
List the products bought by all the customers of 'mycity'
#Edit
This is what I've tried so far:
Select ProductName
from Product
where PID in (
select PID
from LineItem
where OID in(
Select OID
from Order
where CID in(
select CID from customer where city='mycity'
)
)
);
This query however will return all the products bought by all customers from mycity. And the question requires only those products that everyone from 'mycity' have bought.
Not sure how to implement "All in" condition
#Edit2: Finally solved it :) Can someone please verify??
SELECT ProductName FROM Product
INNER JOIN LineItem ON LineItem.PID=Product.PID
INNER JOIN `Order` ON Order.OID=LineItem.OID
INNER JOIN Customer ON Order.CID=Customer.CID
WHERE Customer.City='mycity'
I think this should work
This query is solved in 2 parts: Create a view and query that view
Create view hview as (SELECT distinct count(distinct Customer.CID) as
uniquecustomer, count(distinct Customer.name), product.pid, product.Productname
FROM myorder
INNER JOIN Customer ON myorder.CID = Customer.CID
INNER JOIN LineItem ON myorder.OID = LineItem.oid
INNER JOIN Product ON Product.PID = LineItem.PID
where Customer.city = 'mycity'
group by Product.PID);
select productname from product where pid in(
select PID from hview where uniquecustomer in( SELECT count(distinct Customer.CID)
FROM myorder
INNER JOIN Customer ON myorder.CID = Customer.CID
INNER JOIN LineItem ON myorder.OID = LineItem.oid
INNER JOIN Product ON Product.PID = LineItem.PID
where Customer.city = 'mycity'));
Logic Used: create a view of items with distinct owners from mycity.
Query that view to find items that have distinct owners equal to number of distinct customers in mycity. Every item that has a distinct number of owners equal to the number of distinct customers of mycity are the products that are bought by everyone in mycity.
*myorder is the table name I used instead of order since thats a reserve word.
Better version in a single query:
select p1.productname from Product p1, myorder s1, lineitem l1, customer c1
where l1.pid=p1.pid
and l1.OID=s1.oid
and c1.cid=s1.cid
and c1.city='mycity'
group by p1.ProductName
having count(distinct c1.cid)=(select count(1) from customer c2 where c2.city='mycity');