SQL查询只返回1个结果

时间:2017-11-03 22:39:15

标签: mysql 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表中的其他字段显示products表中符合多种条件的产品。

表架构:

产品(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

1 个答案:

答案 0 :(得分: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语法。