我有一个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'在联系人列表中。
我该怎么做?
答案 0 :(得分:15)
试试这个:
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%'