mysql在查询中使用列值

mspsb9vt  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(300)
+-------------+----------+-----------+
| animal_name | tag_name | tag_group |
+-------------+----------+-----------+
| CatBlue     | cat      | species   |
| CatBlue     | blue     | colour    |
| DogBlue     | dog      | species   |
| DogBlue     | blue     | colour    |
| DogRed      | dog      | species   |
| DogRed      | red      | colour    |
+-------------+----------+-----------+

上表是各种联接表的简化视图。
它是基于所选标记返回结果的系统的一部分。问题是如果选择了蓝色和cat标签,系统当前也会返回dogblue(在sql中使用或)
在mysql中,如何只搜索所有标记组中有一个或多个标记的动物?是否可以在查询中使用标记组列值?
编辑:我想能够要求表中的动物有蓝色和猫的颜色行。其中tag_name=cat或tag_name=blue也会提到狗。

slhcrj9b

slhcrj9b1#

为了得到 animal_name 你可以使用条件聚合

SELECT animal_name
FROM table1
GROUP BY animal_name
HAVING SUM(CASE WHEN tag_name = 'cat' AND tag_group = 'species' THEN 1 ELSE 0 END  ) > 0
AND SUM(CASE WHEN tag_name = 'blue' AND tag_group = 'colour' THEN 1 ELSE 0 END  ) > 0
;

使用mysql,您还可以使用 sum(a=b) , SUM(tag_name = 'blue' AND tag_group = 'colour') 作为速记,在里面使用表达式 sum() 将产生布尔值0/1,真/假
演示
为了蓝狗

SELECT animal_name
FROM table1
GROUP BY animal_name
HAVING SUM(CASE WHEN tag_name = 'dog' AND tag_group = 'species' THEN 1 ELSE 0 END  ) > 0
AND SUM(CASE WHEN tag_name = 'blue' AND tag_group = 'colour' THEN 1 ELSE 0 END  ) > 0
;

根据最后的评论,我需要蓝猫和蓝狗加上 OR 有两个动物名称的标准

SELECT animal_name
FROM table1
GROUP BY animal_name
HAVING (
  SUM(CASE WHEN tag_name = 'dog' AND tag_group = 'species' THEN 1 ELSE 0 END  ) > 0
  AND 
  SUM(CASE WHEN tag_name = 'blue' AND tag_group = 'colour' THEN 1 ELSE 0 END  ) > 0
) OR (
  SUM(CASE WHEN tag_name = 'cat' AND tag_group = 'species' THEN 1 ELSE 0 END  ) > 0
  AND
  SUM(CASE WHEN tag_name = 'blue' AND tag_group = 'colour' THEN 1 ELSE 0 END  ) > 0
)

演示

pgky5nke

pgky5nke2#

您可以将子请求与您的条件一起使用:

SELECT * FROM Table 
INNER JOIN (
SELECT animal_name, sum(tag_name = 'blue' OR tag_name = 'cat') as sum_condition
FROM TABLE
GROUP BY animal_name
HAVING sum_condition = 2) datas USING(animal_name)

编辑以回复评论

SELECT * FROM Table 
INNER JOIN (
SELECT animal_name, sum(tag_name = 'blue' OR (tag_name IN ('cat','dog'))) as sum_condition
FROM TABLE
GROUP BY animal_name
HAVING sum_condition = 2) datas USING(animal_name)

编辑:我的错我忘了一个括号http://sqlfiddle.com/#!9/e9e941/15/0

相关问题