MySQL查询结果和

时间:2016-01-30 22:58:38

标签: mysql sql

我所拥有的是3张牌桌:fruitscategoriesfruit_category

fruits

fruit_id | fruit_name
1          apple
2          orange
3          mango
4          banana
5          lanzones
6          pineapple

fruit_category

fruit_id | cat_id
1          1
2          9
3          7
4          7
5          8
6          9
1          9
2          7
3          9
4          1
5          3
6          5

categories

cat_id | cat_name
1        one
2        two
3        three
4        four
5        five
6        six
7        seven
8        eight
9        nine

当我执行查询以查找类别7或9中的水果时,我得到了正确的结果

fruit_name
apple
orange
mango
banana
pineapple

但是当我使用AND运算符时,我总是得到0结果。下面是我对AND的查询(对于OR而言)

SELECT `o`.`fruit_name`
FROM   `fruits` AS `o`
       JOIN `fruit_category` AS `oc`
         ON `o`.`fruit_id` = `oc`.`fruit_id`
       JOIN `categories` AS `c`
         ON `c`.`cat_id` = `oc`.`cat_id`
WHERE  `oc`.`cat_id` = 7
       AND `oc`.`cat_id` = 9  

2 个答案:

答案 0 :(得分:2)

您应该使用逻辑(一个值不能同时等于两个不相等的值),由in表示:

where `oc`.`cat_id` in ( 7, 9)

相当于:

where `oc`.`cat_id` = 7 or `oc`.`cat_id` = 9

如果您想确保fruit_name属于这两个类别,则应在group by之后使用havingwhere条款(,如上所示,or ):

group by `o`.`fruit_name`
having count(distinct `oc`.`cat_id`) = 2

答案 1 :(得分:1)

SELECT 
  o.fruit_name 
FROM 
  fruits as o 
JOIN 
  fruit_category as oc 
ON 
  o.fruit_id = oc.fruit_id 
JOIN 
  categories as c 
ON 
  c.cat_id = oc.cat_id 
WHERE 
  oc.cat_id IN (7,9)
GROUP BY
  o.fruit_name
HAVING
  COUNT(oc.cat_id) = 2