MySQL查询使用子查询两次

时间:2013-02-22 03:00:42

标签: mysql

我有这个查询

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的表结构,数据在 enter image description here

项目的表格结构,数据在 enter image description here

sites_locations的表结构 enter image description here

位置的表结构,数据在 enter image description here

提前感谢。

3 个答案:

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

可能有一些错误或列名相关错误pl纠正那些错误

答案 1 :(得分: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,因此它可能有语法错误。特别是,您可能需要在某些列名称之前添加别名(最好在列名称之前始终使用别名)。

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