这是一个例子来解释我需要什么:
我有 3 张桌子:
contact: { id, invoices, name } // a contact can have several invoices
invoice: { id, contact, lines, comment } // an invoice can have several lines but only one contact
line: { id, invoice, designation } // a line can have only one invoice
如果用户搜索发票,则希望查询注释、名称和名称字段并仅获取匹配的发票。
所以我这样做了:
SELECT
invoice.id AS id,
invoice.contact AS contact,
invoice.comment AS comment,
FROM invoice
LEFT JOIN contact ON invoice.contact = contact.id
LEFT JOIN line ON line.invoice = invoice.id
WHERE (
contact.name LIKE '%SEARCH_TERM%' OR
invoice.comment LIKE '%SEARCH_TERM%' OR
line.designation LIKE '%SEARCH_TERM%'
)
这项工作除了如果发票有几行与搜索词匹配,我将获得多次相同的发票。
所以我的问题是:即使在多个相关记录中找到搜索词,有没有办法只获得一次发票?
另外,有没有办法只获取发票的字段而不使用别名(我不关心表格联系人和线路,除了搜索)?
如果你知道更好的方法来做到这一点,我很想听听。