select a.*, min(c.price) as Product_Price from tbproduct a left join tbproductbrand b on (a.ProductBrand_Id = b.ProductBrand_Id and a.ProductType_Id = b.ProductType_Id) left join tbproductprice c on (a.Product_Id = c.Product_Id) and a.ProductType_Id = 1 and a.ProductBrand_Id = 2
这句sql,怎么会把a.ProductType_Id不等于1的数据也查出来?
楼主你的左连接有问题,你可以用下边的sql语句试一下:
[code="sql"]select a.*, min(c.price) as Product_Price
from tbproductbrand b, tbproductprice c, tbproduct a
where a.ProductBrand_Id = b.ProductBrand_Id
and a.ProductType_Id = b.ProductType_Id
and a.Product_Id = c.Product_Id
and a.ProductType_Id = 1
and a.ProductBrand_Id = 2[/code]
左连接出错了~
感觉SQL挺乱的 看不出是什么业务逻辑~
强烈建议改善成可读性好的~
select a.*, min(c.price) as Product_Price from tbproduct a left join tbproductbrand b on (a.ProductBrand_Id = b.ProductBrand_Id and a.ProductType_Id = b.ProductType_Id) left join tbproductprice c on (a.Product_Id = c.Product_Id)
where a.ProductType_Id = 1 and a.ProductBrand_Id = 2
不知道你的逻辑是不是这样的
把你的查询条件和连接条件用where 分开
同1楼的,看不出你的逻辑,怎么知道你要的答案?
左连接查询是会给右边的表的null值补出来的。。所以你如果不想将null值查出来就用等值连接不要用left join 或者right join
我认为第二个左连接有问题,第二个左连接的对象不明确,所以导致后面的判断对象不成立。
试试select count(*) from (你的SQL) 看是否真正有查出一条数据,
看了你的sql语句,你都不需要产品品牌的字段,你就不要连接品牌表,
分析SQL,你应该是想获取每个产品的最低价格,你可以先连接两张表查看结果是不是正确,再加其他表的辅助字段,一步一步来,你用到你聚合函数肯定是要分组的。
由于你提供的需求太少,只能授之渔了,相信对你更有好处。