2012-12-16 45 views
0

好的,我正在嘗試的是嘗試從跨越4個獨立列的表中獲取唯一值。通過4個不同的列獲取唯一的值組

例如,我有下面這樣的查詢,其正確的工作列上的一個..

SELECT 
    rest.cuisine1, c.name 
FROM 
    specials 
    INNER JOIN restaurant AS rest ON specials.restaurantid=rest.id 
    INNER JOIN cuisine AS c ON rest.cuisine1=c.id 
WHERE 
    dateend >= CURDATE() 
AND 
    (specials.state='VIC' OR specials.state = 'ALL') 
AND 
    specials.status = 1 
AND 
    rest.status = 1 
GROUP BY 
    c.id; 

現在,rest.cuisine1是包含數據的一列。如預期的那樣,該查詢僅返回來自該列的唯一值。的返回什麼下面是一個例子:

12 Cafe 
18 Asian 
29 Coffee 

有在該表3個更多的列,它們是:

rest.cuisine2 
rest.cuisine3 
rest.cuisine4 

我可以運行上述查詢4次(每列)然後通過PHP運行這些值以從4個不同的結果集中獲取唯一值,但是我想知道是否可以在一個查詢中獲得我想要的全部內容。

+0

我編輯稍微,也許是幫助!但我會檢查你上面的建議。 – Brett

+0

@MahmoudGamal好吧,這工作,但我必須改變選擇'rest.id,c.id,c.name',否則我會得到不正確的ID :) – Brett

+0

@MahmoudGamal嗯,你似乎刪除了你的評論? – Brett

回答

0

這個答案是基於關閉MahmoudGamal的回答,他張貼在評論,他刪除了一些原因。

我用下面的..

SELECT 
    c.id, c.name 
FROM 
    specials 
    INNER JOIN restaurant AS rest ON specials.restaurantid=rest.id 
    INNER JOIN cuisine AS c ON c.id IN (rest.cuisine1, rest.cuisine2, rest.cuisine3, rest.cuisine4) 
WHERE 
    dateend >= CURDATE() 
AND 
    (specials.state='VIC' OR specials.state = 'ALL') 
AND 
    specials.status = 1 
AND 
    rest.status = 1 
GROUP BY 
    c.id; 
1

試試這個

SELECT 
    rest.cuisine1, c.name ,rest.cuisine2 , rest.cuisine3, rest.cuisine4 
FROM 
    specials 
    INNER JOIN restaurant AS rest ON specials.restaurantid=rest.id 
    INNER JOIN cuisine AS c ON rest.cuisine1=c.id 
      INNER JOIN cuisine AS c2 ON rest.cuisine2=c2.id 
      INNER JOIN cuisine AS c3 ON rest.cuisine3=c3.id 
      INNER JOIN cuisine AS c4 ON rest.cuisine4=c4.id 
WHERE 
    dateend >= CURDATE() 
AND 
    (specials.state='VIC' OR specials.state = 'ALL') 
AND 
    specials.status = 1 
AND 
    rest.status = 1 
GROUP BY 
    c.id;