Here is an example to explain what I need:
I have 3 tables:
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
If a user search an invoice, a want to query the comment, designation and name fields and getting only the invoice that match.
So I’ve done this:
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%'
)
This work except that if an invoice has several lines which match the search term, I will get several times the same invoice.
So my question is: is there a way to get only once an invoice even if the search term is find in several related records ?
Also, is there a way to get only the fields of the invoice without using ALIAS (I don’t care about the tables contact and line except for the search) ?
If you know a better way to do that, I’d love to hear it.
1 Answer