2013-08-26 109 views
3

我有兩個表的結構如下選擇以相同的密鑰多個值在多個表

TABLE_1

uid | name | age 
1 | John | 24 
2 | Adam | 35 
3 | Sara | 26 

TABLE_2

id | uid | meta_key | meta_value 
1 | 2 | location | NY 
2 | 2 | school | NYU 
3 | 3 | Location | NY 
4 | 3 | school | XYZ 
6 | 1 | location | NY 
6 | 1 | school | NYU 

什麼我想做的是從table_1中選擇用戶,他們的位置是紐約,學校是紐約大學

這裏是我用,沒有運氣

SELECT 
    tabl_1.uid 
FROM `tabl_1`, `tabl_2` 
WHERE 
    tabl_1.uid = tabl_2.uid 
    AND table_2.meta_key IN ('location', 'school') 
    AND table_2.meta_value IN ('NY', 'NYU') 
ORDER BY tabl_1.uid ASC 

我已經到處找,沒有任何運氣,如果你有一個可行的查詢或將大加讚賞的解決方案的鏈接,謝謝你試一下查詢。

回答

4

你應該嘗試

SELECT t1.uid 
FROM tabl_1 t1 INNER JOIN tabl_2 t2 
ON t1.uid = t2.uid AND t2.meta_key = 'location' AND t2.meta_value = 'NY' 
INNER JOIN tabl_2 t3 
ON t1.uid = t3.uid AND t3.meta_key = 'school' AND t3.meta_value = 'NYU' 

檢查結果上http://sqlfiddle.com/#!2/f35ef/1/0

+0

謝謝馬可,T他的作品完美。 –

1

嘗試: http://sqlfiddle.com/#!2/cc913c/27

SELECT t.* FROM 
(
    SELECT a.uid, a.name, GROUP_CONCAT(b.meta_key, b.meta_value) AS mkv 
    FROM table_1 a 
    LEFT JOIN table_2 b ON b.uid = a.uid 
    GROUP BY a.uid, a.name 
) AS t 
WHERE 
    t.mkv IN ("schoolNYU,locationNY"); 
+0

不錯的想法,但不知道它是否會像加入一樣高效 – skv

+0

更新了答案 - 忘記了順序;爲了高效 - 你可能是對的。謝謝 –

0

嘗試

SELECT table_1.Uid 
FROM table_1 
INNER JOIN table_2 ON table_1.Uid = table_2.Uid 
WHERE (table_2.meta_key = 'location' AND table_2.meta_value = 'NY') 
AND (table_2.meta_key = 'school' AND table_2.meta_valaye = 'NYU') 
相關問題