复杂的mysql选择查询

时间:2012-11-30 17:26:24

标签: mysql

数据:

  1. 形状:shape_id,shape_name
  2. shape_forms :shape_form_id,shape_id,shape_form
  3. shape_form可以是:0 - 圆圈,1 - 正方形,2 - 三角形 - 每个形状的数量不受限制< / LI>

    我需要2个查询来选择

    1. shape_forms中包含圆圈和三角形仅圆圈但不包含正方形或仅包含三角形的所有形状
    2. shape_forms中仅包含三角形的所有形状
    3. 请给我一些解决这个任务的提示! 我限制不使用shape_forms的“group by”但是如果没有合适的解决方案

1 个答案:

答案 0 :(得分:1)

1

select s.shape_id
from shapes s
inner join shape_forms sf on sf.shape_id = s.shape_id
group by s.shape_id
having 
(
   sum(shape_form = 1) = 0
   and sum(shape_form in (0,2)) >= 2
)
or sum(shape_form <> 0) = 0

2

select s.shape_id
from shapes s
inner join shape_forms sf on sf.shape_id = s.shape_id
group by s.shape_id
having sum(shape_form <> 2) = 0