将检查添加到大SQL查询

时间:2012-11-06 19:49:08

标签: php mysql

以下是查询:

SELECT tbl_product.id, tbl_productspecification.id AS specificationId,
            tbl_product.ProductId, tbl_seller.CompanyName, tbl_product.ProductName, tbl_product.Description, mst_Categories.id AS 'Category',
            tbl_productspecification.RetailPrice, tbl_productspecification.SalePrice,
            tbl_product.image, tbl_productspecification.Discount, tbl_product.EndTime, tbl_product.Seller_Id
            FROM tbl_product
            LEFT OUTER JOIN tbl_seller ON tbl_seller.SelId = tbl_product.Seller_Id
            LEFT OUTER JOIN mst_Categories ON (mst_Categories.id = tbl_product.Category OR mst_Categories.id = tbl_product.SubCategory)
            LEFT OUTER JOIN tbl_productspecification ON tbl_productspecification.ProductId = tbl_product.ProductId
            LEFT OUTER JOIN mst_image ON mst_image.Product = tbl_product.ProductId
            LEFT OUTER JOIN tbl_dealinterest ON tbl_dealinterest.ProductId = tbl_product.ProductId
            where tbl_product.Active='y' and tbl_product.StartTime <= '".date("Y-m-d H:i:s")."' and tbl_product.EndTime>'".date("Y-m-d")." 06:00:00'
            ".$subquery." ".$groupby;

tbl_dealinterest表有几个字段:

[BuyerId] [ProductId] [Active] 

我需要过滤掉tbl_dealinterest中符合[BuyerId] [ProductId][Active]不等于n

的记录

我尝试过一些事情,但并未列出所有产品tbl_dealinterest。只有当某人选择了一个选项时才会输入。

1 个答案:

答案 0 :(得分:1)

这应该过滤掉tbl_dealinterest中的任何匹配记录。这假设如果存在记录,tbl_dealinterest.BuyerId永远不会为NULL。

如果没有匹配项,则对tbl_dealinterest表的左连接将返回tbl_dealinterest表中所有字段的NULL值。 where子句中的“tbl_dealinterest.BuyerId IS NULL”将过滤掉匹配项。

SELECT tbl_product.id, tbl_productspecification.id AS specificationId,
            tbl_product.ProductId, tbl_seller.CompanyName, tbl_product.ProductName, tbl_product.Description, mst_Categories.id AS 'Category',
            tbl_productspecification.RetailPrice, tbl_productspecification.SalePrice,
            tbl_product.image, tbl_productspecification.Discount, tbl_product.EndTime, tbl_product.Seller_Id
            FROM tbl_product
            LEFT OUTER JOIN tbl_seller ON tbl_seller.SelId = tbl_product.Seller_Id
            LEFT OUTER JOIN mst_Categories ON (mst_Categories.id = tbl_product.Category OR mst_Categories.id = tbl_product.SubCategory)
            LEFT OUTER JOIN tbl_productspecification ON tbl_productspecification.ProductId = tbl_product.ProductId
            LEFT OUTER JOIN mst_image ON mst_image.Product = tbl_product.ProductId
            LEFT OUTER JOIN tbl_dealinterest ON tbl_dealinterest.BuyerId = tbl_product.BuyerId AND tbl_dealinterest.ProductId = tbl_product.ProductId AND tbl_dealinterest.active <> 'n'
            where tbl_product.Active='y' and tbl_product.StartTime <= '".date("Y-m-d H:i:s")."' and tbl_product.EndTime>'".date("Y-m-d")." 06:00:00'
            AND tbl_dealinterest.BuyerId IS NULL
            ".$subquery." ".$groupby;