如何简化这个可怕的查询?

时间:2013-07-23 02:07:56

标签: mysql

我已经明白这个问题,修改它变得太笨重了,我确信它也变得相当低效。

我有一个项目表,可能有任何可变数量的属性,因此这些属性列在小表中...项目ID和属性ID通常构成索引,属性表将有其他信息。实质上,它们用于将大量项目过滤到至少相关的子集。

SELECT * FROM item
INNER JOIN itemwearTable 
ON (id=itemwearTable.itemID AND itemwearTable.wearlocID=1)
WHERE item.id IN (
 SELECT id FROM item
 LEFT JOIN itemalignTable 
 ON item.id=itemalignTable.itemID
 WHERE
   itemalignTable.itemID IS NULL OR
  (itemalignTable.itemID=item.id AND itemalignTable.alignID=1)
)
AND 
item.id IN (
 SELECT id FROM item
 LEFT JOIN itemgenderTable 
 ON itemgenderTable.itemID=item.id
 WHERE
  itemgenderTable.itemID IS NULL OR
  (itemgenderTable.itemID=item.id AND itemgenderTable.genderID=1)
)
AND
(item.id IN (
 SELECT id FROM item
 LEFT JOIN itemgenreTable 
 ON item.id=itemgenreTable.itemid
 WHERE
  itemgenreTable.itemid IS NULL OR
  (itemgenreTable.itemID=item.id AND itemgenreTable.genreID=1)
)
OR
item.id IN (
  SELECT id from item
  LEFT JOIN itemclassTable 
  ON item.id=itemclassTable.itemid
  WHERE
   itemclassTable.itemid IS NULL OR
  (itemclassTable.itemID=item.id AND itemclassTable.classID=1)
))
AND 
item.id IN (
 SELECT id from item
 LEFT JOIN itemlocTable ON
  item.id=itemlocTable.itemid
  WHERE
   itemlocTable.itemid IS NULL OR
   (itemlocTable.itemID=item.id AND itemlocTable.locID=1)
)
AND
item.minlvl <= 50
ORDER BY item.sdesc

注意我在很多地方使用了= 1来替换通常是生成查询的脚本的一部分的php变量。问题是,虽然这些项目用于缩小结果,我有另一个表itemaffTable,其中包含与item.id = itemaffTable.itemID匹配的其他数据(例如金额),但我似乎无法看到如何获得插入时没有严重搞乱已经存在的东西。

感谢任何帮助。

2 个答案:

答案 0 :(得分:3)

我认为应该这样做:

SELECT DISTINCT i.*, iwt.* FROM item i
INNER JOIN itemwearTable iwt ON i.id=iwt.itemID 
LEFT JOIN itemalignTable iat ON i.id = iat.itemID
LEFT JOIN itemgenderTable igt ON i.id = igt.itemID
LEFT JOIN itemgenreTable igrt ON i.id = igrt.itemID
LEFT JOIN itemclassTable ict ON i.id = ict.itemID
LEFT JOIN itemlocTable ilt ON i.id = ilt.itemID
WHERE (iat.itemID IS NULL OR iat.alignID = 1)
AND (igt.itemID IS NULL OR igt.genderID = 1)
AND (igrt.itemID IS NULL OR igrt.genreID = 1)
AND (ict.itemID IS NULL OR ict.classID = 1)
AND (ilt.itemID IS NULL OR ilt.locID = 1)
AND i.minlvl <= 50
AND iwt.wearlocID=1
ORDER BY i.sdesc

答案 1 :(得分:1)

这样的事情应该有效。

SELECT item.*, itemwearTable.* FROM item
INNER JOIN itemwearTable
  ON (id=itemwearTable.itemID AND itemwearTable.wearlocID=1)
LEFT JOIN itemalignTable
  ON item.id=itemalignTable.itemID
LEFT JOIN itemgenderTable
  ON itemgenderTable.itemID=item.id
LEFT JOIN itemgenreTable
  ON item.id=itemgenreTable.itemid
LEFT JOIN itemclassTable
  ON item.id=itemclassTable.itemid
LEFT JOIN itemlocTable
  ON item.id=itemlocTable.itemid
WHERE (itemalignTable.itemID IS NULL OR itemalignTable.alignID=1)
  AND (itemgenderTable.itemID IS NULL OR itemgenderTable.genderID=1)
  AND (itemlocTable.itemid IS NULL OR itemlocTable.locID=1)
  AND ((itemgenreTable.itemid IS NULL OR itemgenreTable.genreID=1)
      OR (itemclassTable.itemid IS NULL OR itemclassTable.classID=1))
  AND item.minlvl <= 50
ORDER BY item.sdesc