仅选择其他表中的行数大于0的行

时间:2012-07-05 14:48:31

标签: mysql

我的数据库中有2个表:

Products:
--------------------------------------------------
|   id    |   product_name    |   manufacturer   |
--------------------------------------------------

Products_photos:
-----------------------------------------------
|   id    |   product_id    |   image_name    |
-----------------------------------------------

我想选择所有产品,其中Product_photos计数大于0。 我怎么能这样做?

@Edit: 我不想为Products输出添加Products_photos的结果。我只想显示产品中的条目,其中包含任何图像。对不起我的英文:)

感谢您的帮助

4 个答案:

答案 0 :(得分:0)

SELECT P.* FROM Products AS P INNER JOIN Products_Photos AS PP ON P.id=PP.id

另一种方法,效率更低但可能更好,您可以

SELECT P.* FROM Products AS P
WHERE P.id IN (SELECT DISTINCT id FROM Product_photos)

答案 1 :(得分:0)

SELECT p.id, p.product_name, p.manufacturer
FROM Products p
     INNER JOIN Products_photos i on i.product_id = p.id

答案 2 :(得分:0)

你可以做到

Select P.id, P.product_name, P.manufacturer
from Products P 
INNER JOIN Products_photos Pp on P.Id = Pp.product_id

对于Inner Join,它只会返回加入的行,这意味着Products_photos表中至少有一个值。

答案 3 :(得分:0)

我认为,就查询效率而言,已经提供的加入解决方案是最好的选择。但为了清楚起见 - 在准确表达你的要求方面 - 我会选择这样的方法:

select * from products p
where exists (select * from products_photos pp where pp.product_id = p.id)