MySql query to fetch data in 3rd table from 1st table - mysql

I have three tables.
Fee table which contains Fee_id and Fee_name...
Session table which contains session_id and fee_id(foreign key).
classfee_charge table which contains session_id(foreign key),class_id(fo[![enter image description here][1]][1]reign key) and amount.
I have to store amount of fee classwise in classfee_charge table.
How to fetch fee_name in classfee_charge table?

You can put the current session_id (1 in the code bellow) after you group by Fee_name to have the aggregate data for each kind of expense :
SELECT
Fee.Fee_id,
Fee.Fee_name
FROM
Fee, Session
WHERE
Fee.Fee_id = Session.Fee_id
AND
Session.session_id = 1
GROUP BY
Fee.Fee_name
The result :
Fee_id Fee_name
1 Expense
SQL Fiddle for more details

SELECT f.Fee_name from fee f
INNER join session s
on s.Fee_id=f.Fee_id
INNER join classfee_charge cf
on cf.session_id=s.session_id

Related

SQL query same table twice but get one output column only mysql

I need to list the two ENTITY_ID's (by querying the RELATIONS table with WHERE between two dates) related to each SOURCE/ACCOUNT pairs in the RELATIONS table.
- ENTITIES table
ENTITY_ID (PK)
ENTITY_NAME
- ACCOUNTS table
SOURCE (PK)
ACCOUNT (PK)
ENTITY_ID (FK)
- RELATIONS table
RELATION_ID (PK)
SOURCE_1 (FK)
ACCOUNT_1 (FK)
SOURCE_2 (FK)
ACCOUNT_2 (FK)
TIMESTAMP
The query below retrieves the ENTITY_ID of one SOURCE/ACCOUNT pair (SOURCE_1/ACCOUNT_1), but I'd also need the ENTITY_ID of SOURCE_2/ACCOUNT_2, not as second column in the output, but as a second row (value).
SELECT A.ENTITY_ID
FROM RELATIONS R
JOIN ACCOUNTS A
ON R.SOURCE_1 = A.SOURCE
AND R.ACCOUNT_1 = A.ACCOUNT
WHERE R.TIMESTAMP >= DATETIME1 AND R.TIMESTAMP < DATETIME2
Example of output needed (1 column, 2 values):
ENTITY_ID
Output record #1 1234
Output record #2 1235
If you need the values in different rows, then you can do:
SELECT A.ENTITY_ID
FROM RELATIONS R JOIN
ACCOUNTS A
ON (R.SOURCE_1 = A.SOURCE AND
R.ACCOUNT_1 = A.ACCOUNT
) OR
(R.SOURCE_2 = A.SOURCE AND
R.ACCOUNT_2 = A.ACCOUNT
)
WHERE R.TIMESTAMP >= DATETIME1 AND
R.TIMESTAMP < DATETIME2;
ORs generally kill the performance of JOINs, but this will work if your data is not very big.

Need help on query sum total quantity show wrong output

Process:
When user buy item and check out then there's cart and cart items table to store the transaction.
1 cart_id have many item which stored in cart items table.
After purchase succeed, then will generate a purchase order id and stored in purchase order table .
In purchase order table, id_cart and status will be stored.
From here, i am trying to calculate quantity based on id_product or id branch or etc from the purchase made.
There is receiving and ordered quantity field, which in some cases quantity received field might be null, so i will take ordered quantity value.
This is my query
SELECT id_product,sum(DISTINCT(COALESCE(received_qty, quantity)))
FROM (SELECT C.id_cart,C.received_qty,C.quantity , P.id_product,
PO.id_purchase_order, PO.status
FROM (SELECT * FROM cart_items WHERE id_cart IN (SELECT id_cart FROM purchase_orders)) AS C
LEFT JOIN products as P on p.id_product = c.id_product
LEFT JOIN purchase_orders AS PO ON C.id_cart = PO.id_cart ) AS A
GROUP By A.id_product
Table data
The cart id in will be duplicated based on product's supplier. Because need to track and send separately to supplier.
Result
By right the product id for 1212 should be 1 and 1223 is 2, total qty =3.
What's wrong with my query ?
Your outer joins seem to cause multiplication of your data, but there are so many unnecessary layers of fluff in your query that I cant make it out exactly.
How about just this:
SELECT id_product, sum(COALESCE(received_qty, quantity)) AS Nmbr
FROM cart_items
GROUP BY id_product
If you want to make sure the cart is in your purchase_orders:
SELECT c.id_product, sum(COALESCE(c.received_qty, c.quantity)) AS Nmbr
FROM cart_items c
JOIN (SELECT DISTINCT id_cart FROM purchase_orders) p ON p.id_cart = c.id_cart
GROUP BY c.id_product

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.

Join table on pattern match

I have been struggling with this for several hours, so any feedback or advise is very welcome.
I have three tables:
users
id name email
1 test test#test.com
2 test2 test2#test.com
pets
pet_id pet_name user_id
1 sam 2
2 sally 1
transactions
trans_id custom
1 1
2 pid2
3 pid1
OK, what I would like to do is get transaction data relating to the user. So in the 'transactions' table 'custom' value 1 would relate to 'users' with the id. Thats the simple bit...
'Transactions' with 'pid' relate to the pets id, so 'pid2' relates to sally, whose user is user id 1. So I need to join the transaction table when custom relates to the user id or if its prefixed with 'pid' and the appending value relates to the 'pet_id'.
Here's an example of the result I would like:
Transactions relating to user_id 1:
trans_id 1, custom 1
trans_id 2 custom pid2 (this is because the pets owner is user_id 1)
Here is where I am with my attempt at the moment:
SELECT users.*, transactions.*
FROM users
LEFT JOIN transactions on users.id = transactions.custom
This is where I'm falling over:
SELECT users.*, transactions.*
FROM users
LEFT JOIN pets ON pets.user_id = user.id
LEFT JOIN transactions on (users.id = transactions.custom
OR pets.pet_id REGEXP '^pid(transactions.custom)')
If you can't change the table design and the prefix pid is fixed you could use
OR (
pets.pet_id = SUBSTR(transactions.custom, 3)
AND SUBSTR(transactions.custom, 1 FOR 3) = 'pid')
see documentation to SUBSTR and because MySQL automatically converts numbers to strings as necessary, and vice versa, see: http://dev.mysql.com/doc/refman/5.7/en/type-conversion.html
You HAVE to refactor Your DB. Current structure will guarantee of speed problems.
Table transactions should looks like
CREATE TABLE transactions
(
id Int NOT NULL, (id of transaction)
pet_id Int, (can be null)
user_id Int (can be null)
other columns here...
)
;

Select from 3 joined tables with condition?

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.