Help with a query count with multiple conditions?
I'm not great with sql and I've tried this a lot of different ways and can't come up with a reliable solution. Basically I have
I need a query that will tell how many unique instances of nid show up for a combination of tid. Basically count with two or more conditionals and only return the number of rows that met all of the conditions.开发者_运维技巧 The combination of tid s can be more than 2 or more numbers...this will obviously require adding to the query and this is fine (I dont expect a query that accepts an array if that makes sense)...I just need the logic of the query sound.
I need to be able to pass the tid 's of 35 & 45 and receive back "2" meaning two complete matches. The tid 35 & 45 both appear with nid 4 & 10, but since tid 45 doesn't appear in nid 2, it should not count it. I hope that makes sense.
When testing against:
26,27 it should reply "2"
35,27 should reply "2"
31,35 should reply "1"
26,27,45 should reply "1"
Showing the nid
: 4 and 10
SELECT nid
FROM taxonomy_index
WHERE tid IN (35,45) --- list of tid to check
GROUP BY nid
HAVING COUNT(DISTINCT tid) = 2 --- count of numbers in list
Counting them:
SELECT COUNT(*)
FROM
( SELECT nid
FROM taxonomy_index
WHERE tid IN (35,45)
GROUP BY nid
HAVING COUNT(DISTINCT tid) = 2
) AS grp
If the combination (nid,tid)
is unique, then the COUNT(DISTINCT tid)
can be replaced with COUNT(*)
.
Another way is:
SELECT COUNT(DISTINCT nid)
FROM taxonomy_index a
WHERE NOT EXISTS
( SELECT *
FROM taxonomy_index b
WHERE b.tid IN (35,45)
AND NOT EXISTS
( SELECT *
FROM taxonomy_index c
WHERE c.tid = b.tid
AND c.nid = a.nid
)
)
精彩评论