2017-11-03 258 views
0

查詢將返回唯一1的結果,請大家幫忙SQL查詢只返回1個結果

select 
p.products_id, pd.products_name 
from 
products_description pd, 
products_to_categories p2c, 
products p 
where 
EXISTS (SELECT p2pef.products_id 
        FROM products_to_products_extra_fields p2pef 
        WHERE p2pef.products_extra_fields_id = '78' 
       and p2pef.products_extra_fields_value = 'tak' 
        and p.products_id = p2pef.products_id) 
and 
EXISTS (SELECT p2pef.products_id 
        FROM products_to_products_extra_fields p2pef 
        WHERE p2pef.products_extra_fields_id = '94' 
        and p2pef.products_extra_fields_value = 'tak' 
        and p.products_id = p2pef.products_id)   


and p.products_status = '1' 
and p.products_id = pd.products_id 
and p.products_id = p2c.products_id 
and pd.language_id = '4' 
and p2c.categories_id = '26' 
group by p.products_id 

你認爲怎麼樣使用EXISTS此查詢?

您可能有另一種想法來顯示來自products_to_products_extra_fields表的其他字段滿足多個條件的產品表中的產品。

表模式:

產品(4行)

_________________________ 
products_id 
_________________________ 

1 
2 
3 
4 

products_to_products_extra_fields(8行)

___________________________________________________________________ 
products_id products_extra_fields_id products_extra_fields_value 
___________________________________________________________________ 
1 94 tak 

1 78 tak 

2 94 tak 

2 78 tak 

3 94 tak 

3 78 tak 

4 94 nie 

4 78 tak 

有效的查詢應該返回(3行)

_______________ 
products_id 
_______________ 

1 

2 

3 
+0

'EXISTS'部分似乎沒問題。問題可能是您的其他過濾器只選擇了一個'product_id' –

+0

的確,所有* product_ids *都不帶'EXISTS'子句? – Parfait

+0

嗨。 「滿足幾個條件」是什麼意思?您似乎對輸入「條件」的某種表示形式和輸出查詢感興趣,但您沒有足夠詳細地解釋我們可以知道什麼是正確的答案。請同時閱讀[mcve]並採取行動。事實上,你的問題到底是什麼? – philipxy

回答

1

呦ü可以使用一個having子句來實現這一目標還有:

select  p.products_id 
from  products p 
inner join products_description pd 
     on p.products_id = pd.products_id 
inner join products_to_categories p2c 
     on p.products_id = p2c.products_id 
inner join products_to_products_extra_fields p2pef 
     on p.products_id = p2pef.products_id 
where  p.products_status = '1' 
and   pd.language_id = '4' 
and   p2c.categories_id = '26' 
and   p2pef.products_extra_fields_value = 'tak' 
and   p2pef.products_extra_fields_id in ('78', '94') 
group by p.products_id 
having  count(distinct p2pef.products_extra_fields_id) = 2 

..但結果是一樣的。如果您的記錄數量少於預期,請確保您期望在輸出中的所有產品也符合有關狀態,語言和類別的其他條件。

注意:對錶達式連接條件使用join語法。

+0

我相信它並不完全等同於任何數據。如果他對'product_id'有額外的字段行(78,'tak'),(94,'nie')感興趣,那麼你的方法可能很難延伸到正確的工作。 –

+1

事實上,對於其他條件,必須寫另一個「有條件」的條件。例如:count(當p2pef.products_extra_fields_value ='tak'且products_extra_fields_id ='78'時的唯一情況,則當p2pef.products_extra_fields_value ='nie'且products_extra_fields_id ='94'時爲1,則2結束) – trincot