我正在尝试对查询进行性能调整,并且需要帮助
我们需要根据多种因素在网站上提取数据,从而导致复杂的查询工作正常,但价格昂贵。我们拥有所有正确的索引。
我遇到的问题是在查询中删除DISTINCT的使用(这似乎是瓶颈)。
我不是SQL专家,我想我已经尽力了。
任何有助于简化此查询并删除DISTINCT(或不使用GROUP BY)的帮助将不胜感激。谢谢。
SELECT DISTINCT t2.PK
FROM categories t0
JOIN cat2catrel t1 ON t1.SourcePK = t0.PK
JOIN categories t2 ON t1.TargetPK = t2.PK
JOIN cat2catrel t3 ON t3.SourcePK = t2.PK
JOIN categories t4 ON t3.TargetPK = t4.PK
JOIN cat2prodrel t5 ON t5.SourcePK = t4.PK
JOIN products t6 ON t5.TargetPK = t6.PK
JOIN stocklevels t7 ON t7.productcode = t6.code
JOIN relativeinventory t8 ON t7.p_inventory = t8.PK
JOIN warehouses t9 ON t7.warehouse = t9.PK
JOIN pos2warehouserel t10 ON t10.TargetPK = t9.PK
JOIN pos2warehouserel t10 ON t10.TargetPK = t9.PK
JOIN pointofservice item_t11 ON t10.SourcePK = t11.PK
WHERE ( t0.code = 'code'
AND t8.nventorystatus IN (1111)
AND t11.name = 'ABC')
AND ((t0.TypePkString IN (1, 2, 3, 4)
AND (( t0.catalogversion IN (1, 2, 3)))
AND t1.TypePkString=1000
AND t2.TypePkString IN (1, 2, 3, 4)
AND (( t2.catalogversion IN (1, 2)))
AND t3.TypePkString=300
AND t4.TypePkString IN (6, 7, 8)
AND (( t4.catalogversion IN (5, 6)))
AND t5.TypePkString=500
AND t6.TypePkString=600
AND t7.TypePkString=200
AND t8.TypePkString=700
AND t9.TypePkString IN (3, 7)
AND t10.TypePkString=900
AND t11.TypePkString=750 ));
当前,此查询工作正常,并提供了我想要的结果。我只是不想使用DISTINCT或GROUP BY而仍然获得独特的结果。
数据库:MySQL 6.3
答案 0 :(得分:0)
您仅选择t2.pk,它似乎是类别表中的主键。如果这是正确的话,那么您的Join会产生重复。通常,在这种情况下摆脱DISTINCT的最简单解决方案是从要选择的表开始,并确保将INNER JOINING绑定到该表。但是,看来您实际上已经在执行此操作了,但是您正在复制联接...即t0和t2是同一张表,这对我来说是一个很大的危险信号。尝试这样的事情:
SELECT t0.PK
FROM categories t0
INNER JOIN cat2catrel t1 ON t1.SourcePK = t0.PK AND t1.TargetPK = t0.PK
INNER JOIN cat2catrel t3 ON t3.SourcePK = t0.PK
INNER JOIN categories t4 ON t3.TargetPK = t4.PK
INNER JOIN cat2prodrel t5 ON t5.SourcePK = t4.PK
INNER JOIN products t6 ON t5.TargetPK = t6.PK
INNER JOIN stocklevels t7 ON t7.productcode = t6.code
INNER JOIN relativeinventory t8 ON t7.p_inventory = t8.PK
INNER JOIN warehouses t9 ON t7.warehouse = t9.PK
INNER JOIN pos2warehouserel t10 ON t10.TargetPK = t9.PK
INNER JOIN pos2warehouserel t10 ON t10.TargetPK = t9.PK
INNER JOIN pointofservice item_t11 ON t10.SourcePK = t11.PK
WHERE ( t0.code = 'code'
AND t8.nventorystatus IN (1111)
AND t11.name = 'ABC')
AND ((t0.TypePkString IN (1, 2, 3, 4)
AND (( t0.catalogversion IN (1, 2, 3)))
AND t1.TypePkString=1000
AND t2.TypePkString IN (1, 2, 3, 4)
AND (( t2.catalogversion IN (1, 2)))
AND t3.TypePkString=300
AND t4.TypePkString IN (6, 7, 8)
AND (( t4.catalogversion IN (5, 6)))
AND t5.TypePkString=500
AND t6.TypePkString=600
AND t7.TypePkString=200
AND t8.TypePkString=700
AND t9.TypePkString IN (3, 7)
AND t10.TypePkString=900
AND t11.TypePkString=750 ));
但是,我看到其他表格重复出现,例如“ pos2warehouserel”。 只应声明表一次并为其分配一个别名。