I have three table a, b and c in mysql. a has events, b has ticket categories for each event of a, and c has tickets each of b. So a pure relational datbase. What i'm trying to find out is the count of total ticket categories and total tickets each of the event a has.
I had tried like this:
SELECT a. * , COUNT( b.at_id ) AS totTktCat, COUNT( c.bt_id ) AS totTkts
FROM a_table a
JOIN b_table b
USING ( at_id )
JOIN c_table c
USING ( bt_id )
GROUP BY a.at_id
but no luck, the totals are wrong.
A little help from the mysql gurus will help.
I have added an sql fiddle: http://sqlfiddle.com/#!9/ec8b0/1.
I'm getting total like this
at_id at_cat at_event totTktCat totTkts
1 1 aevent1 6 6
2 2 aevent2 2 2
which is wrong.
MY expected output is
at_id at_cat at_event COUNT(bt_ticktgrp) COUNT(ct_tickets)
2 2 aevent2 2 4
For the sql fiddle: http://sqlfiddle.com/#!9/ebc9ea6
As per your given description, i have written query like this..
SELECT a.at_id,a.at_cat,a.at_event,count(*) as bt_ticktgrp,(SELECT count(*) FROM `b_table` b JOIN `c_table` c ON c.bt_id=b.bt_id where b.at_id=a.at_id) as ct_tickets FROM `a_table` a JOIN `b_table` b
ON a.at_id=b.at_id
GROUP BY a.at_cat;
Here i have grouped outer one with table a and inner one with table c by mapping it with table b.
i.e With each id of table a it joins table b and table c.
Hope this solves your query.
Related
I try to select all from 2 tables in mysql database with the sum of total cost in the second table
i have a table name tbl_project contain
db_id db_projectname and other column
1 test
2 test2
3 test3
second table name tbl_activities contain
db_id db_projectname db_totalcost
1 test 200
2 test 300
3 test2 800
the out put i want is
test 500
test2 800
test3
i try this query but it didn't give me that result
select tbl_project.db_id, tbl_project.db_projectname,tbl_project.db_location,tbl_project.db_client,tbl_project.db_transferredto,tbl_project.db_psd,tbl_project.db_pdd,tbl_project.db_duration,tbl_project.db_past,tbl_project.db_padd,tbl_project.db_aduration,tbl_project.db_percent,tbl_project.db_pnote,tbl_project.db_user,tbl_project.db_cpercentage,tbl_project.db_epercentage,tbl_project.db_mpercentage,tbl_project.db_status,tbl_project.db_offer,tbl_project.db_sheet,tbl_project.db_invoice,tbl_project.db_po,sum(tbl_activities.db_totalcost) as total_cost from tbl_project,tbl_activities where
tbl_project.db_projectname=tbl_activities.db_projectname
it give me
test but sum of another project and only one project not all
You needed to use LEFT JOIN & GROUP BY
SELECT
tbl_project.db_id,
tbl_project.db_projectname,
tbl_project.db_location,
tbl_project.db_client,
tbl_project.db_transferredto,
tbl_project.db_psd,
tbl_project.db_pdd,
tbl_project.db_duration,
tbl_project.db_past,
tbl_project.db_padd,
tbl_project.db_aduration,
tbl_project.db_percent,
tbl_project.db_pnote,
tbl_project.db_user,
tbl_project.db_cpercentage,
tbl_project.db_epercentage,
tbl_project.db_mpercentage,
tbl_project.db_status,
tbl_project.db_offer,
tbl_project.db_sheet,
tbl_project.db_invoice,
tbl_project.db_po,
sum(
tbl_activities.db_totalcost
) AS total_cost
FROM
tbl_project
LEFT JOIN tbl_activities ON tbl_project.db_projectname = tbl_activities.db_projectname
GROUP BY tbl_project.db_id
Note:
Using aggregate function (e.g. SUM,COUNT..) without GROUP BY collapses the result set into a single row.
try this;
SELECT
db_projectname.db_projectname,SUM(tbl_activities.db_totalcost) AS total_cost
FROM db_projectname
LEFT JOIN tbl_activities
ON
db_projectname.db_projectname = tbl_activities.db_projectname
GROUP BY db_projectname.db_projectname
I know that this question already asked many times here but after all I could't found my answer that what I want.
My Question is:
I have two tables and the structure of these tables is as:
table1:
item_id, store,title,available,shipping
table2:
item_id, review_rate,user_id,review_title
These tables should be join as one to many relation.
For example if the data in these tables is as:
table1:
item_id store title available shipping
-------------------------------------------------------
11 glasses ..........................
12 dresses ..........................
.
.
.
table2:
item_id review_rate user_id review_title
--------------------------------------------------
11 3 10023 good item
11 5 10024 nice item
12 1 10024 nice one
.
.
.
then the result should be as after joining:
afterJoin:
item_id store title available shipping rate people_reviewed
-----------------------------------------------------------------------
11 .................................... 4 2
12 .................................... 1 1
The query I tried to join is as:
CREATE OR REPLACE VIEW afterJoin AS
SELECT i.*,round(AVG(r.review_rate)) as rate,count(r.user_id) as people_reviewed
FROM table1 i
RIGHT JOIN table2 r ON i.item_id = r.item_id
but this return only one row.
Your query is missing a GROUP BY clause. Without it your database is aggregating all of the records together.
SELECT i.*, round(AVG(r.review_rate)) as rate, count(r.user_id) as people_reviewed
FROM table1 i
RIGHT JOIN table2 r ON i.item_id = r.item_id
GROUP BY i.item_id
The GROUP BY instructs the db to aggregate for each item_id.
I'm trying to find a patient's appointments and messages count. My table records are like below 3 table patient, appointments and messages
Patient table
pid fname lname
1 john sid
2 rother ford
3 megan rough
4 louis kane
appointments table
id pid appointment_date
1 1 2015-08-04
2 2 2015-08-05
3 1 2015-08-06
4 1 2015-08-07
5 3 2015-08-07
6 2 2015-08-08
7 4 2015-08-13
8 1 2015-08-12
Messages table
id pid description message_date
1 2 join 2015-08-04
2 2 update 2015-08-05
3 3 join 2015-08-05
4 4 update 2015-08-10
5 3 test 2015-08-07
So if write query to find counts i'm getting wrong values
SELECT pd.fname,pd.lname , pd.pid, COUNT( a.id ) AS app_cnt, COUNT( m.id ) AS mes_cnt
FROM patient pd
LEFT OUTER JOIN appointments a ON a.pid = pd.pid
LEFT OUTER JOIN messages m ON m.pid = pd.pid
GROUP BY pd.pid
ORDER BY pd.pid
fname lname pid app_cnt mes_cnt
john sid 1 4 0
rother ford 2 4 4
megan rough 3 2 2
louis kane 4 1 1
Here pid 1 have 4 appointments and 0 messages, pid 2 have 2 appointments and 2 messages but getting wrong values.
Can someone please help to resolve this issue. I'm not interested in writing sub queries for this.
Functionality looks simple but I'm really facing problem for writing query.
Anymore suggestions please.
After thoroughly analysing your problem and tables, It cannot be done directly using simple query as LEFT OUTER JOIN is returning some superfluous records, that's why to filter it, you will have to use temporary table and modify the query as:
Select temp.fname, temp.lname, temp.pid, a_count, count(m.pid) as m_count from
(SELECT fname,lname,pd.pid, count(a.pid) as a_count
FROM patients pd
LEFT OUTER JOIN appointments a ON a.pid = pd.pid group by pd.pid) temp
LEFT OUTER JOIN messages m ON m.pid = temp.pid
group by temp.pid
Explanation:
It will join patients and appointments table and group them by pid so that messages from message table do not repeat for each patients.pid.
The wrong result is as a result of left outer join as it is giving wrong results for this query
SELECT *
FROM patients pd
LEFT OUTER JOIN appointments a ON a.pid = pd.pid
LEFT OUTER JOIN messages m ON m.pid = pd.pid
Since we need to limit the results of first two joins, hence temporary table is necessary.
I have multiple tables with orders and deliveries and I want to get only open orders (only those orders that do not have records in delivery table).
So, my tables look like:
Orders table (sh_comenzi):
id partner
1 Partner X
2 Partner Y
3 Partner Z
4 Partner Q
Order lines table (sh_comenzi_pos) where idc is the id of sh_comenzi table
id idc cPos quantity
1 1 1 5
2 1 2 10
3 1 3 20
4 2 1 10
5 2 2 15
6 3 1 10
7 3 2 5
8 3 3 8
9 4 1 15
The deliveries items table is (sh_delivery_items)
id idc cPos
1 1 1
2 1 3
3 2 2
4 3 1
5 3 2
6 3 3
The desired result should give me an output of open orders just like this:
id partner
1 Partner X
2 Partner Y
4 Partner Q
The result doesn't have to keep track o quantities, just on lines level. If one line from orders exists in sh_delivery_items then that line is closed.
I tried something like this:
SELECT DISTINCT sh_comenzi.id, partner FROM sh_comenzi
LEFT JOIN sh_comenzi_pos ON sh_comenzi.id = sh_comenzi_pos.idc
LEFT JOIN sh_delivery_items ON (sh_comenzi_pos.idc = sh_delivery_items.idc AND sh_comenzi_pos.cPos = sh_delivery_items.cPos)
WHERE sh_comenzi.id IS NOT NULL
ORDER BY sh_comenzi.id DESC
Could someone help me?
This is the query you need:
SELECT DISTINCT c.*
FROM sh_comenzi c
INNER JOIN sh_comenzi_pos p
ON c.id = p.idc
LEFT JOIN sh_delivery_items di # 'di' from 'delivery items'
ON p.idc = di.idc AND p.cPos = di.cPos
WHERE di.id IS NULL # keep only not-delivered items
How it works
It combines all the orders (table sh_comenzi) with their line items (table sh_comenzi_pos). The INNER JOIN will leave out the empty orders (if any); if you need them then use LEFT JOIN instead.
Next, each row (order, line item) is combined with the delivery information (table sh_delivery_items) using the pair of columns (idc, cPos). The LEFT JOIN ensures all the rows from the left side table (or result set) appear in the final result set; if a row from the right side table cannot be found to match the row from the left, a row full of NULLs is used instead. This happens for the line items that were not delivered yet (there is no record for them in sh_delivery_items).
Then, the WHERE clause keeps only the rows having NULLs in the di table (sh_delivery_items), i.e. the line items that were not delivered, together with the orders that own them.
Finally, SELECT DISTINCT c.* selects only the columns from the orders table (sh_comenzi) and DISTINCT ensures each order appear only once. Otherwise, each order appears once for each of its line items that was not delivered.
Complete the query yourself with the desired ORDER BY clause.
I have three tables where table_2 is the middle(connected) between table_1 and table_3
tables
table_id
...
...
table_rest
rest_id
table_id
...
rest
rest_id
...
...
And the query to select I use
SELECT m.table_id, table_name
FROM tables m
JOIN table_rest mr
ON m.table_id = mr.table_id
WHERE rest_id = '$rest_id'
What I need now is to join in this query another table reserv
id
...
status
To check if status is 0, 1,or 2 to not show me anything if there is no status this mean there is no record to show me. In other words this is resserved system where I show on screen few tables. If status is 0,1,2 thats mean the table is taken. If nothing is found for status this mean that there is no record for table and can be shown to user.
EDIT: Sample scenario
tables
table_id
1
2
3
4
5
rest
rest_id
1
2
table_rest
table_id | rest_id
1 2
2 2
3 2
4 2
5 2
So the query that is above will generate 5 tables for rest_id=2 and none for rest_id=1
So now I have another table
reserv
id | status
1 0
2 1
3 2
So in this table reserv currently are saved 3 tables. The idea is to show me other two whit id=4 and id=5 because they are not in table reserv and don't have any status.
Hope is a little bit more clear now.
You have to point from table reserv to which table is beign booked, let's call it reserv.table_id
SELECT m.table_id, table_name
FROM tables m
JOIN table_rest mr
ON m.table_id = mr.table_id
left join reserv
on reserv.table_id = m.id
WHERE rest_id = '$rest_id'
and reserv.status is null (*note)
*note use 'is' or 'is not' depending of your needs, as far as I read, first seems that you want !=, later that what you want is =
It's better if you provide sample data or sqlfiddle. Based on what I realize: Is this what you want:
select tables.table_id, rest.rest_id
from tables
left join table_rest on table_rest.table_id = tables.table_id
left join rest on rest.rest_id = table_rest.rest_id
where rest.rest_id = '$rest_id'
and tables.table_id not in (select id from reserv)