0

我有以下表格:

**products** which has these fields: id,product,price,added_date
**products_to_categories** which has these fields: id,product_id,category_id
**adverts_to_categories** -> id,advert_id,category_id
**adverts** which has these fields: id,advert_name,added_date,location

我无法执行 sql,它将返回给我所有属于类别 14 并且由位于伦敦的广告拥有的产品。所以我有 4 张桌子和 2 个条件 - 来自第 14 类,产品的所有者来自伦敦。我尝试了许多变体来执行 sql,但没有一个结果是正确的。我是否需要使用 Join 以及 which Join - left,right,full?正确的 sql 会是什么样子?提前感谢您的帮助,抱歉让您感到厌烦:)

这是我到目前为止所尝试的:

SELECT p.id, product, price, category_id, 
       p.added_date, adverts.location, adverts.id 
FROM products p, 
     products_to_categories ptc, 
     adverts, 
     adverts_to_categories ac 
WHERE ptc.category_id = "14" 
  AND ptc.product_id=p.id 
  AND ac.advert_id=adverts.id 
  AND adverts.location= "London"
4

2 回答 2

1

非常基本的逻辑

Select * from Products P
INNER JOIN Products_To_Categories PTC ON P.ID = PTC.Product_ID
INNER JOIN Adverts_to_Categories ATC ON ATC.Category_Id = PTC.Category_ID
INNER JOIN Adverts AD on AD.ID = ATC.Advert_ID
WHERE PTC.Category_ID = 14 and AD.Location = 'LONDON' 

如果您想要其他表中不存在的表中的记录,则只需要左连接或右连接。
例如,如果您想要所有产品,即使一个记录甚至是那些没有类别的产品,那么您将使用左连接而不是内部连接。

于 2012-06-05T21:56:27.973 回答
1

以下语句应返回产品表中 ID 为 14 的类别中的所有列以及位于伦敦的所有广告:

select p.* from products p
inner join products_to_categories pc on p.id = pc.product_id
inner join adverts_to_categories ac on pc.category_id = ac.category_id
inner join adverts a on a.id = ac.advert_id
where pc.category_id = 14
and ac.location = 'London';

如果您经常执行这些基于字符串的查询,您应该记住将索引添加到列位置。

于 2012-06-05T22:00:22.620 回答