1

我有这个查询

SELECT itemID, locationParentID, locationID, categoryParentID, categoryID, itemTitle, itemDetails, itemAttributes, itemPictures, itemFeatured, itemSpotlight, itemAdded 
FROM items 
WHERE locationID NOT IN
    (SELECT locationID 
    FROM sites_locations 
    WHERE siteID != 2) AND items.siteID IN('1,2') AND itemStatus = '1' 
    AND itemAdded > '1356048000'

它工作正常但是当我执行这个查询时它失败了

SELECT itemID, locationParentID, locationID, categoryParentID, categoryID, 
itemTitle, itemDetails, itemAttributes, itemPictures, itemFeatured, itemSpotlight, itemAdded FROM items 
WHERE locationID NOT IN
    (SELECT locationID 
     FROM sites_locations WHERE siteID != 2) 
     AND categoryID NOT IN (SELECT categoryID FROM sites_categories 
     WHERE siteID != 2) AND items.siteID IN('1,2') AND itemStatus = '1' 
     AND itemAdded > '1356048000' 

这里的区别是我添加了子句

AND categoryID NOT IN(SELECT categoryID FROM sites_categories 
WHERE siteID != ".$cfg['site']['siteID'].") 

任何想法为什么这不起作用?

甚至更好的是加入查询来帮助优化它。

sites_categories 的表结构,数据在 在此处输入图像描述

项目的表结构,数据在 在此处输入图像描述

sites_locations 的表结构 在此处输入图像描述

位置的表结构,数据在 在此处输入图像描述

提前致谢。

4

3 回答 3

1

试试这个

SELECT i.itemID, i.locationParentID, i.locationID, i.categoryParentID, i.categoryID, 
i.itemTitle, i.itemDetails, i.itemAttributes, i.itemPictures, i.itemFeatured, i.itemSpotlight, i.itemAdded 
FROM    items i,  sites_locations sl, sites_categories sc  
WHERE i.locationID = sl.locationID 
AND i.categoryID = sc.categoryID   
AND i.siteID = 1 AND i.itemStatus = '1' 
AND i.itemAdded > '1356048000'

它可能有一些错误或与列名相关的错误请纠正这些错误

于 2013-02-22T03:50:28.383 回答
0

你可以把它变成这样的连接:

SELECT i.itemID, i.locationParentID, i.locationID, i.categoryParentID, i.categoryID, 
       i.itemTitle, i.itemDetails, i.itemAttributes, i.itemPictures, i.itemFeatured,
       i.itemSpotlight, i.itemAdded
FROM items i left outer join
     sites_locations sl
     on i.locationID = sl.locationId and sl.siteId <> 2 left outer join
     sites_categories sc
     on i.categoryID = sc.categoryId and sc.siteId <> 2
WHERE sl.locationID is NULL and sc.categoryId is NULL and
      i.siteID IN (1, 2) AND i.itemStatus = 1 AND i.itemAdded > 1356048000

这也可能具有更好的性能。

注意:我没有测试过这个 SQL,所以它可能有语法错误。特别是,您可能需要在某些列名之前添加别名(最好在列名之前始终使用别名)。

于 2013-02-22T03:25:42.410 回答
0

解决了

SELECT itemID, locationParentID, locationID, categoryParentID, categoryID, itemTitle, itemDetails, itemAttributes, itemPictures, itemFeatured, itemSpotlight, itemAdded FROM items WHERE items.siteID IN('1,2') AND items.locationID = (SELECT locationID FROM sites_locations sl WHERE sl.locationID = items.locationID AND siteID = '2') AND items.categoryID = (SELECT categoryID FROM sites_categories sc WHERE sc.categoryID = items.categoryID AND siteID = '2') AND itemStatus = '1' AND itemAdded > '1356048000' ORDER BY itemID DESC LIMIT 15 
于 2013-02-22T03:54:27.913 回答