2013-11-22 89 views
0

我有一個MySQL表像這樣MySQL查詢建議與訪問ID

ownerlisting_access_id property_id mainaccess_id subaccess_id access_value 
62      2    35  41   Yes 
64      2    35  36   Yes 
123      4    35  41  Yes 
125      4    35  36  Yes 
306      7    35  41  Yes 
307      7    35  42  Yes 
308      7    35  36  Yes 

我想要一個查詢,將使用subaccess_id(41,42,36)和mainaccess_id(35)給我這個輸出 -

ownerlisting_access_id property_id mainaccess_id subaccess_id access_value 
306      7    35    41    Yes 
307      7    35    42    Yes 
308      7    35    36    Yes 

我需要使用子訪問ID與41,42,以獲得作爲PROPERTY_ID 7,36

+1

您在編寫的查詢中遇到了什麼問題?請向我們展示您的查詢。 –

+0

SELECT * FROM'rt_ownerlisting_access' WHERE'mainaccess_id' = 35 AND('subaccess_id' = 41 OR'subaccess_id' = 42 OR'subaccess_id' = 36) 我得到所有記錄 SELECT * FROM'rt_ownerlisting_access' WHERE' mainaccess_id' = 35 AND('subaccess_id' = 41 AND'subaccess_id' = 42 AND'subaccess_id' = 36) 我沒有記錄 – mikejohnvino

+0

它應該返回所有記錄,因爲所有記錄都有subaccess_id = 41,42或36 。 –

回答

-1
SELECT MAX(DISTINCT property_ID) AS property_ID, mainaccess_id, 
MAX(DISTINCT subaccess_id) AS subaccess_id, MAX(DISTINCT access_value) 
FROM tableName GROUP BY mainaccess_id ORDER BY mainaccess_id 
+0

爲什麼倒投這個? –

-1
SELECT property_ID, mainaccess_id, subaccess_id, access_value 
FROM tableName t1 
WHERE t1.mainaccess_id = 35 
AND (t1.subaccess_id = 41 OR t1.subaccess_id = 42 OR t1.subaccess_id = 36) 
AND t1.property_ID = (SELECT MAX(t2.property_ID) 
        FROM tableName t2 
        WHERE t2.mainaccess_id = 35 
        AND (t2.subaccess_id = 41 OR t2.subaccess_id = 42 OR t2.subaccess_id = 36)) 
+0

我猜對了property_id = 7不知道? – TheStackHasGrownIntoTheHeap

1

獲得問題答案的最快方法是描述問題,而不是僅顯示需要的結果。目前還不清楚你想要的輸出背後的邏輯是什麼。我想你需要每個組subaccess_id最高的property_id行。如果是的話這裏是查詢:

select * from t 
join (select subaccess_id, max(property_id) MAX_property_id 
     from t 
     where mainaccess_id=35 
       and 
       subaccess_id in (41,42,36) 
     group by subaccess_id 
    ) t1 
     on t.subaccess_id=t1.subaccess_id 
     and 
     t.property_id=t1.MAX_property_id 

SQLFiddle demo

而且,這裏是輸出結果,你需要查詢:)但我想這不會解決你的問題:

select * from t where property_id=7 
0

試試這個:

SELECT table1.* FROM (
select property_id, group_concat(DISTINCT subaccess_id ORDER BY subaccess_id) as list 
from table1 as t1 group by property_id 
) a, table1 
WHERE a.property_id = table1.property_id 
AND a.list = '36,41,42' 

工作查詢: http://sqlfiddle.com/#!2/4744ea/2