我是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方法从发票表中选择适当的行并将其包含在结果集中。
如果仅复制数据,性能会更好吗?
谢谢,
丹恩
最佳答案
这样的事情怎么样?
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;
关于mysql - MySQL冗余索引的替代方案?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9899523/