简体   繁体   中英

mysql join and count rows

I have two tables I need to query

First table 'archive_agent_booking':

|account_no|week|year|description|price|date|job_id|
----------------------------------------------------

Second Table is 'invoice_additions':

|account_no|week|year|description|amended_price|amend_date|
-----------------------------------------------------------

What I am aiming to do is get the following data for each week number in each database in descending order keeping in mind that the week numbers may not exist in both tables.

The data needs to appear as below:

Week No:(this will come from both tables even if week number does not exist in one of the tables.)

Appointments:(this will come from the first table and just be a COUNT() of the number of week occurrences.)

Invoice Adjustments:(this will come from the second table and be a count of the number of week occurrences as before.)

The select query I have got so far is for one table only:

"SELECT week, year,
COUNT(week) AS week_no FROM archive_agent_booking
WHERE account_no='$account_no'
GROUP BY week, year
ORDER BY week DESC"

I am having trouble linking the second table to this query so that it will count both week columns in each table.

SELECT 
    week, 
    year,
    COUNT(week) AS week_no 
FROM archive_agent_booking
left join invoice_additions on invoice_additions.week = archive_agent_booking.week
WHERE account_no='$account_no'
GROUP BY week, year
ORDER BY week DESC

Since you dont have a foreign key you can join on week

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM