select语句中的mysql案例

时间:2013-07-07 08:49:11

标签: mysql

我有两张桌子

1)访问表

visit_id     |   visit_date    |   premises_name
   1             2012-04-25        abc
   2             2012-04-25        xyz
   3             2012-04-25        yio

2)样本表

visit_id    |   sample_id     |   item_name
   1               abc_332          lmn
   1               xyz_342          pqr
   2               lsl_324          plk

每次访问都可以有多个样本

我想要输出以下结果的查询

visit_id   |  visit_date |  is_sample_taken
   1          2012-04-25         YES
   2          2012-04-25         YES
   3          2012-04-25         NO

我搜索了很多,但无法解决问题。请帮忙

2 个答案:

答案 0 :(得分:2)

尝试类似:

select visit_id , visit_date , case when sum(case when b.visit_id is NULL then 0 else 1 end) > 0 then  'YES' else 'NO' end as sampletaken
from visittable as a LEFT OUTER JOIN sampltetable as b on a.visit_id = b.visit_id   
group by visit_id , visit_date

答案 1 :(得分:0)

在Hiren Dhaduk的帮助/提示下回答我得到了我的问题的解决方案

SELECT v.v_id, v.v_date, (
    CASE WHEN EXISTS (
        SELECT sample_id
        FROM sample
        WHERE visit_id = v.v_id
    )
    THEN 1 ELSE 0 END
) AS is_sample_taken
FROM visit v