2013-03-27 46 views
2

我想知道所有連接的值是否在另一個表中。集團由+所有在...?

例子:

id childId 
1 2 
1 3 
1 4 
2 6 
2 7 
2 8 
2 9 

childIds 
2 
3 
4 
6 
7 



**desired result:** 

id allChildrenInChildIds 
1 True 
2 False 

什麼是做到這一點的最好方法是什麼?

回答

1

SQL Fiddle DEMO


select id, case when sum(TrueorFalse) = count(1) then 'true' 
       else 'false' end 
from (
select id, case when exists (select 1 from ChildIDs where id = childid) then 1 
      else 0 
      end as TrueOrFalse 
from child) A 
group by A.id 

使用時存在(選擇... ...從)

+0

這一個似乎是最容易理解和產生所需的結果... 謝謝! – Vigrond 2013-03-28 01:05:12

1

如果您運行此查詢

SELECT id, GROUP_CONCAT(childId) 
FROM table 
WHERE childId NOT IN (2,3,4,5,6,7,8) 
GROUP BY id 

結果中的任何想法將是錯誤的。我添加了GROUP_CONCAT,因此您可以確定哪個childId不在集合中。如果一個id不在結果中,那麼它是真的。

+0

NOT IN(2,3,4,5,6,7,8)也可能不在(SELECT id從childIds) – miah 2013-03-27 03:55:48

1

試試這個

SELECT 
    ID 
    ,MIN(allChildrenInChildIds) 
FROM 
(
    SELECT id, 
    CASE WHEN childId IN (SELECT childIds FROM Table2) THEN 'TRUE' ELSE 'FALSE' 
    END AS allChildrenInChildIds 
    FROM Table1 
) result 
GROUP BY ID 
1

像這樣的事情?

select 
    id, 
    case when exists (
    select c.childid 
    from Child as c 
    where c.id = ids.id 
    and not exists (
     select * 
     from Childids 
     where c.childid = Childids.id 
    )) then 'No' else 'Yes' end as WereAllChildrenFound 
from ids 
1

這個怎麼樣?


select id , case when count(c.childid) <> count(ci.childid) then 'false' else 'true' end as allChildrenInChildIds 
from Child c 
left join ChildIds ci 
on c.childid = ci.childid 
group by id