0

这是一个例子来解释我需要什么:

我有 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%'
)

这项工作除了如果发票有几行与搜索词匹配,我将获得多次相同的发票。

所以我的问题是:即使在多个相关记录中找到搜索词,有没有办法只获得一次发票?

另外,有没有办法只获取发票的字段而不使用别名(我不关心表格联系人和线路,除了搜索)?

如果你知道更好的方法来做到这一点,我很想听听。

4

3 回答 3

1
SELECT 
  DISTINCT invoice.*
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%'
)
于 2012-06-03T16:08:25.217 回答
1

是的。您可以通过向 WHERE 子句添加子查询来做到这一点:

SELECT invoice.id AS id, invoice.contact AS contact, invoice.comment AS comment, 
FROM invoice LEFT JOIN
     contact
     ON invoice.contact = contact.id 
WHERE contact.name LIKE '%SEARCH_TERM%' OR 
      invoice.comment LIKE '%SEARCH_TERM%' OR
      invoice.id in (select line.invoice
                     from line
                     where line.designation LIKE '%SEARCH_TERM%')

您还可以使用子查询在 FROM 子句中构造它:

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
     (select distinct line.invoice
      from line
      where line.designation LIKE '%SEARCH_TERM%'
     ) line
     on line.invoice = invoice.id
WHERE contact.name LIKE '%SEARCH_TERM%' OR 
      invoice.comment LIKE '%SEARCH_TERM%' OR
      line.invoice is not null

在这种结构中,如果不止一行有搜索词,则需要使用 distinct 关键字来防止重复行。

于 2012-06-03T16:11:21.677 回答
0

DISTINCT 会起作用吗?

SELECT DISTINCT
  i.id, 
  i.contact, 
  i.comment, 
FROM invoice AS i
  LEFT JOIN contact ON i.contact = contact.id 
  LEFT JOIN line ON line.invoice = i.id
WHERE (
  contact.name LIKE '%SEARCH_TERM%' OR 
  i.comment LIKE '%SEARCH_TERM%' OR 
  line.designation LIKE '%SEARCH_TERM%'
)
于 2012-06-03T16:10:26.300 回答