当我使用这个查询时,一切都很好。 5结果为0.3587秒。
SELECT `prod_combined`.`sku`, `prod_combined`.`titel`, `prod_combined`.`preis_vk`,
`prod_combined`.`link`
FROM `prod_combined`
WHERE
(
prod_combined.sku IN
(
SELECT
prod_combined.sku FROM
(
SELECT prod_combined.sku FROM prod_billiger
INNER JOIN
prod_combined ON prod_combined.sku = prod_billiger.sku
WHERE rangGesamt = 1
AND prod_combined.aktiv = 1
) q
JOIN prod_combined ON prod_combined.sku = q.sku)
)
AND (aktiv = 1)
LIMIT 0,5
但是当我使用此查询时,它会运行大约3分钟。
SELECT `prod_combined`.`sku`, `prod_combined`.`titel`, `prod_combined`.`preis_vk`,
`prod_combined`.`link`
FROM `prod_combined`
WHERE
(
prod_combined.sku IN
(
SELECT
prod_combined.sku FROM
(
SELECT prod_combined.sku FROM prod_billiger
INNER JOIN
prod_combined ON prod_combined.sku = prod_billiger.sku
WHERE rangGesamt = 1
AND prod_combined.aktiv = 1
) q
JOIN prod_combined ON prod_combined.sku = q.sku)
)
AND (aktiv = 1)
我想做什么: 获取所有首位产品(prod_billiger.rangGesamt)。我在“prod_billiger”表中获得此信息。其他产品信息来自prod_combined。
有没有办法,加快速度?我是否需要推翻整个查询?
此致 chucky2305
答案 0 :(得分:0)
这样的事情对你有用吗?
SELECT pc.sku, pc.titel, pc.preis_vk, pc.link
FROM prod_combined AS pc
WHERE pc.sku IN (
SELECT sku
FROM prod_billiger
WHERE rangGesamt = 1
)
AND pc.aktiv=1
我添加了prod_combined(prod_combined AS pc
)的同义词,只是为了使select
语句更加简洁。
如果您的表很小,或者您有rangGesamt和/或aktiv的索引,这将很快运行。
答案 1 :(得分:0)
重写您的查询会让我:
SELECT pc.sku, pc.titel, pc.preis_vk, pc.link pc
FROM prod_combined pc
WHERE
(
pc.sku IN
(
SELECT
pc2.sku FROM
(
SELECT pc2.sku FROM
prod_billiger pb
INNER JOIN prod_combined pc2 ON pc2.sku = pb.sku
WHERE pb.rangGesamt = 1
AND pc2.aktiv = 1
) q
JOIN prod_combined pc3 ON pc3.sku = q.sku
)
)
AND pc.aktiv = 1
;
,这可能与以下内容相同:
SELECT pc.sku, pc.titel, pc.preis_vk, pc.link pc
FROM prod_combined pc
WHERE pc.sku IN (
SELECT q.sku
FROM (
SELECT pc2.sku FROM
prod_billiger pb
INNER JOIN prod_combined pc2 ON pc2.sku = pb.sku
WHERE pb.rangGesamt = 1
AND pc2.aktiv = 1
) q
)
AND pc.aktiv = 1
;
可以进一步简化为:
SELECT pc.sku, pc.titel, pc.preis_vk, pc.link pc
FROM prod_combined pc
WHERE EXISTS (
SELECT *
FROM prod_billiger pb
INNER JOIN prod_combined pc2 ON pc2.sku = pb.sku
WHERE pb.rangGesamt = 1 AND pc2.aktiv = 1
AND pc.sku = pb.sku;
)
AND pc.aktiv = 1
;
如果“sku”是prod_combined的主键,则子查询甚至可以进一步减少,只包含“prod_billiger”。
SELECT pc.sku, pc.titel, pc.preis_vk, pc.link pc
FROM prod_combined pc
WHERE EXISTS (
SELECT *
FROM prod_billiger pb
WHERE pc.sku = pb.sku;
AND pb.rangGesamt = 1 AND pc2.aktiv = 1
)
AND pc.aktiv = 1
;
或多或少等同于:
SELECT pc.sku, pc.titel, pc.preis_vk, pc.link pc
FROM prod_combined pc
WHERE pc.sku IN (
SELECT sku
FROM prod_billiger pb
WHERE pb.rangGesamt = 1
)
AND pc.aktiv = 1
;
如果sku也是prod_billiger的主要(或候选)键,事情甚至可以进一步减少到:
SELECT pc.sku, pc.titel, pc.preis_vk, pc.link pc
FROM prod_combined pc
JOIN prod_billiger pb ON pc.sku = pb.sku
WHERE pb.rangGesamt = 1
AND pc.aktiv = 1
;