MySQL Redundant索引替代?

时间:2012-03-28 00:19:57

标签: mysql sql

我是MySQL新手,我正在运行此查询,

SELECT item_id,amount FROM db.invoice_line WHERE item_id = 'xxx'  
OR item_id = 'yyy'
...
AND invoice_id IN 
    (SELECT id_invoices FROM db.invoices 
    WHERE customer = 'zzzz' 
    AND transaction_date > DATE_SUB(NOW(), INTERVAL 6 MONTH)
    AND sales_rep = 'aaa') ORDER BY item_id;

即,从另一个表中找到外键的表中选择一些列。

问题是我希望在结果中还有客户名称。但是,在发票行表中找不到客户名称,它可以在发票表中找到。

虽然我可以在创建表和插入表时天真地创建重复索引,但我想知道是否有一种SQL方法可以从发票表中选择正确的行并将其放在结果集中。

如果我只是复制数据,性能会更好吗?

谢谢, 戴恩

2 个答案:

答案 0 :(得分:1)

这样的事情怎么样?

SELECT
    invoice_line.item_id,
    invoice_line.amount,
    invoices.customer_name
FROM db.invoice_line
INNER JOIN db.invoices
    ON invoice_line.invoice_id = invoices.id_invoices
WHERE invoices.customer = 'zzzz'
AND invoices.transaction_date > DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH)
AND invoices.sales_rep = 'aaa'
AND (invoice_line.item_id = 'xxx' OR invoice_line.item_id = 'yyy')
ORDER BY invoice_line.item_id;

答案 1 :(得分:1)

使用表之间的连接来实现结果。