0

I have two tables, one that has transaction information such as id, status, price and date. I have another table that stores the number of items in that order as individual rows. So, say transaction 2 has 10 items, there will be 10 rows in the second table of different items. What im trying to do is run a query that lists transactions and the number of items sold in that transaction. I imagine this would require a count on the second table, but im not entirely sure of how to do it. This is the basic layout of the database

transaction id, date, price, discount, status
items: id, transaction_id, item_name, email, date_ordered, hash

Thanks in advance for all the help.

2 Answers 2

1

Group by the columns in the transaction table you want to select. Then add a count of the items

select t.id, count(i.id) as item_count
from transaction t
left join items i on i.transaction_id = t.id
group by t.id
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that seems to work. Ill mark as answer as soon as I can
0

You can do a left join on both tables like below

select t.*, tab.total_order
from transaction t
left join
(
select transaction_id, count(*) as total_order
from items
group by transaction_id
) tab on t.id = tab.transaction_id

2 Comments

Hmm, I realized that the answer above only returns one result (as it doesnt have a group by). For the page I was working on it was fine, but on the page im working on now, I need all the rows. Im trying to use your code, but for some reason its telling me the fields dont exist for tab.transaction_id.
@Shaun, ahh! that's a silly one. You got that error cause transaction_id was not included in the select list of the inner query. Try the edited query and it should work fine now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.