我的mysql数据库中有一个名为“events”的表:
+-----+-----------+------------------------------+------------+
| ID | CATEGORY | NAME | TYPE |
+-----+-----------+------------------------------+------------+
| 1 | 1 | Concert | music |
| 2 | 2 | Basketball match | indoors |
| 3 | 1 | Theather play | outdoors |
| 4 | 1 | Concert | outdoors |
+-----+-----------+------------------------------+------------+
我需要一个查询来计算类别1的事件,哪种类型是音乐,还有室外 意味着从上面的表中计数应该只有1:有三个事件与类别1 但只有“音乐会”有户外和音乐类型(ID 1和ID 4)。
那个查询是什么?可以这样做吗?
答案 0 :(得分:3)
试试这个:
SELECT count(DISTINCT e1.name)
FROM `events` AS e1
JOIN `events` AS e2 ON e1.name = e2.name
WHERE e1.category = 1
AND e2.category = 1
AND e1.type = 'music'
AND e2.type = 'outdoor'
或者更难理解的方式,但比前一种方式更快:
SELECT count(*) FROM (
SELECT `name`
FROM `events`
WHERE `category` = 1
GROUP BY `name`
HAVING SUM( `type` = 'music') * SUM( `type` = 'outdoor' ) >= 1
) AS notNeeded
答案 1 :(得分:2)
对于2个标准,我会使用Alin的答案。您可以使用更多数字的方法。
SELECT COUNT(*)
FROM (SELECT `name`
FROM `events`
WHERE `category` = 1
AND `type` IN ( 'outdoors', 'music' )
GROUP BY `name`
HAVING COUNT(DISTINCT `type`) = 2) t
答案 2 :(得分:1)
尝试此查询
Select count(*), group_concat(TYPE SEPARATOR ',') as types
from events where category = 1
HAVING LOCATE('music', types) and LOCATE('outdoors', types)
答案 3 :(得分:-1)
尝试:
SELECT * FROM `events` AS e1
LEFT JOIN `events` AS e2 USING (`name`)
WHERE e1.`category` = 1 AND e2.`category` = 1 AND e1.`type` = 'music' AND e2.`type` = 'outdoors'
答案 4 :(得分:-1)
SELECT COUNT(*)
FROM table
WHERE category=1
AND type='music' AND type IN (SELECT type
FROM table
WHERE type = 'outdoor')
一行保持重置我的连接。用?我会尝试发表评论
答案 5 :(得分:-2)
从Category ='1'并输入('music','outdoor')
的事件中选择计数(不同ID)作为'eventcount'