Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql select where count = 0

Tags:

mysql

In my db, I have a "sales" table and a "sales_item". Sometimes, something goes wrong and the sale is recorded but not the sales item's.
So I'm trying to get the salesID from my table "sales" that haven't got any rows in the sales_item table.

Here's the mysql query I thought would work, but it doesn't:

SELECT s.*
FROM sales s NATURAL JOIN sales_item si
WHERE s.date like '" . ((isset($_GET['date'])) ? $_GET['date'] : date("Y-m-d")) . "%'
AND s.sales_id like '" . ((isset($_GET['shop'])) ? $_GET['shop'] : substr($_COOKIE['shop'], 0, 3)) ."%'
HAVING count(si.sales_item_id) = 0;

Any thoughts?

like image 292
OSdave Avatar asked Jun 15 '10 12:06

OSdave


2 Answers

Having always used with Group By

GROUP BY si.sales_item_id
HAVING count(si.sales_item_id) = 0;
like image 61
Salil Avatar answered Oct 21 '22 12:10

Salil


Where does the table alias v does come from? Showing the table definition would be a really good idea ;)

It has to be a left join:

SELECT *
FROM table1
LEFT JOIN table2 ON(table1.id = table2.table1_id)
WHERE table2.table1_id IS NULL

Table1 is your sales-Table and table2 is you sales_item

like image 24
Tobias P. Avatar answered Oct 21 '22 13:10

Tobias P.