/    Sign up×
Community /Pin to ProfileBookmark

SQL Where COUNT > 0

I have this code, works well.

I want it to only show records where TTL is greater than 0.

If I add “AND TTL > 0 ” in the WHERE clause, it errors. Help please.

“`
SELECT p.ID, p.ProductName, p.Image, COUNT(*) as `TTL`

FROM `products` p
JOIN `inventory` i ON p.ID = i.ProductID

WHERE i.DateAdded > 0 AND p.ProductStatus = 0 AND p.ID != 60

GROUP By p.ID
“`

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@NogDogSep 03.2020 — Yeah, TTL doesn't get calculated until after the WHERE is applied, so doesn't really exist at that point. However, how would COUNT(*) ever be 0? Seems to me it would always be at least 1. If you were doing a SUM() or AVG() on some field, then that would make sense, but just counting rows.... 🤷‍♂️
Copy linkTweet thisAlerts:
@sibertSep 04.2020 — Normally you can move the count and use "HAVING" instead of "WHERE". I do not know if it works in MySQL as I have not any data to test with.

``<i>
</i>SELECT p.ID, p.ProductName, p.Image
FROM
products p
JOIN
inventory i ON p.ID = i.ProductID
HAVING count(*)&gt;0
GROUP By p.ID<i>
</i>
``

https://www.mysqltutorial.org/mysql-having.aspx/
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.7,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...