MySQL在查询中使用列值

时间:2018-05-31 15:35:29

标签: mysql

+-------------+----------+-----------+
| animal_name | tag_name | tag_group |
+-------------+----------+-----------+
| CatBlue     | cat      | species   |
| CatBlue     | blue     | colour    |
| DogBlue     | dog      | species   |
| DogBlue     | blue     | colour    |
| DogRed      | dog      | species   |
| DogRed      | red      | colour    |
+-------------+----------+-----------+

上表是各种联合表的简化视图。

它是根据所选标签返回结果的系统的一部分。问题是如果选择蓝色和猫标签,系统当前也会返回DogBlue。 (它在SQL中使用OR)

在MySQL中,如何只搜索所有标签组中包含一个或多个标签的动物?是否可以在查询中使用tag_group列值?

编辑: 我希望能够请求表格行,其中动物的颜色为蓝色,而物种 cat 。 WHERE tag_name = cat OR tag_name = blue也会带来狗。

2 个答案:

答案 0 :(得分:1)

要获得拥有所有这些属性的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 ; ,您可以使用条件聚合,例如

sum(a=b)

使用Mysql你也可以使用SUM(tag_name = 'blue' AND tag_group = 'colour')sum()作为简写,使用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 ; 中的表达式将得到一个布尔值0/1,true / false

Demo

For Blue dog

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 ) 条件以同时拥有动物名称

{{1}}

Demo

答案 1 :(得分:0)

您可以根据条件使用子请求:

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