从mysql查询中获取正确的结果

时间:2012-06-05 21:49:44

标签: sql

我有以下表格:

**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和哪个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"

2 个答案:

答案 0 :(得分: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' 

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

答案 1 :(得分: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';

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