10

我有一个 SQL 查询,它使用 GROUP_CONCAT 让所有人都附加到某个订单。有没有办法可以在 GROUP_CONCAT 字段中进行搜索?

SELECT orders.orderID, 
GROUP_CONCAT(contacts.firstName, " ", contacts.lastName) AS attachedContacts
FROM (orders)
JOIN contacts ON orders.contactID=contacts.contactID
GROUP BY orders.orderID
ORDER BY orders.orderID DESC

我想添加类似WHERE attachedContacts LIKE '%Eric%', 以仅列出附加了“Eric”的订单,但仍将所有其他联系人包含在查询中。

查询返回如下数据:

orderID atachedContacts
01      Eric Siegel, John Smith
02      Jason Jackson, Bill O'Neil
03      Eric Siegel, Jason Jackson, Neil O'Ryan

我希望查询返回第 01 和 03 行,因为“Eric”在联系人列表中。

我怎样才能做到这一点?

4

1 回答 1

25

试试这个:

SELECT orders.orderID, 
GROUP_CONCAT(contacts.firstName, " ", contacts.lastName) AS attachedContacts
FROM orders
JOIN contacts ON orders.contactID=contacts.contactID
GROUP BY orders.orderID DESC
HAVING attachedContacts LIKE '%Eric%'
于 2010-09-27T18:55:20.137 回答