Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding difference in row count of two tables in MySQL

Tags:

sql

mysql

count

sum

I have two tables, one stores the products and quantity we have bought, the other stores the sells. The current stock is therefore the sum of all the quantity columns in the bought table minus the number of rows in the sells table. How can this be expressed in MySQL. Remember that there are many different products.

EDIT: To make it harder, I have another requirement. I have the bought table, the sold table, but I also have the products table. I want a list of all the products, and I want to know the quantity available of each product. The problem with the current answers is that they only return the products that we have sold or bought already. I want all the products.

like image 604
Marius Avatar asked Oct 28 '08 12:10

Marius


People also ask

How do I compare the number of rows in SQL?

SELECT (SELECT count(*) from table1)=(SELECT count(*) from table2) AS RowCountResult; as a boolean result will be returned.

How different number of rows can be counted?

If you need a quick way to count rows that contain data, select all the cells in the first column of that data (it may not be column A). Just click the column header. The status bar, in the lower-right corner of your Excel window, will tell you the row count.

What is the difference between count () and RowCount ()?

So, @@RowCount is used to check number of rows affected only after a query execution. But Count(*) is a function, which will return number of rows fetched from the SELECT Query only. After SELECT statement also giving number of row retrived from the query.


1 Answers

Try this


SELECT inv_t.product_id, inventory_total-nvl(sales_total,0)
FROM 
  (SELECT product_id, sum(quantity) as inventory_total
   FROM inventory
   GROUP BY product_id) inv_t LEFT OUTER JOIN
  (SELECT product_id, count(*) AS sales_total 
   FROM sales 
   GROUP BY product_id) sale_t
  ON (inv_t.product_id = sale_t.product_id)

This is a better solution than a few of the other ones posted, which do not account for the fact that some products may not have any corresponding rows in the sales table. You want to make sure that such products also show up in the results.

NVL is an Oracle-specific function that returns the value of the first argument, unless it's null, in which case it returns the value of the second argument. There are equivalent functions in all commercial DBMSes -- you can use CASE in MySQL to the same effect.

like image 184
SquareCog Avatar answered Sep 23 '22 16:09

SquareCog