2012-01-24 58 views
1

好吧,我從一個PHP腳本中獲得一個包含多個用戶ID的數組。選擇所有用戶ID匹配的編號

現在我有這樣的MySQL表:

+ - - - - - - - - - - - + - - - - - + 
¦ fk_conversation  ¦ fk_user ¦ 
+ - - - - - - - - - - - + - - - - - + 
¦ 1      ¦  2  ¦ 
+ - - - - - - - - - - - + - - - - - + 
¦ 1      ¦  3  ¦ 
+ - - - - - - - - - - - + - - - - - + 
¦ 1      ¦  4  ¦ 
+ - - - - - - - - - - - + - - - - - + 
¦ 2      ¦  2  ¦ 
+ - - - - - - - - - - - + - - - - - + 
¦ 2      ¦  4  ¦ 
+ - - - - - - - - - - - + - - - - - + 

如果我得到陣列(2,4),我需要得到fk_conversation鍵= 2,但如果我得到的數組(2,3,4)我應該得到的fk_conversation鍵= 1.

我總是想得到fk_conversation ID所有連接的fk_user ID在陣列中。

回答

2
select fk_conversation 
from my_table 
where fk_user in (ARRAY VALUES) 
and fk_conversation in (
    select fk_conversation 
    from my_table 
    group by fk_conversation having count(distinct fk_user) = ARRAY SIZE 
) 
group by fk_conversation 
having count(distinct fk_user) = ARRAY SIZE; 
+0

感謝,這解決了我的問題:d – Pascal

0

嘗試:

select fk_conversation 
    from table 
    where fk_user in (comma separated array_values) 
    group by fk_conversation 
    having count(fk_conversation) = array_size 
+0

不,不行。它會返回兩個fk_conversation ID。但最後我只應該得到fk_conversation id,它被分配給數組中的所有id,但也僅限於數組中的所有id。 – Pascal

+0

你寫了正確的sql嗎?這裏是我的榜樣... SELECT fk_conversation 測試從 WHERE fk_user IN(2,3,4) GROUP BY fk_conversation HAVING COUNT(fk_conversation)= 3個 – Daniel