在MySQL中构建查询以查找客户名称

时间:2016-03-16 21:48:48

标签: mysql sql database

我在MySQL中有SQL statemet,但问题是它只接受一个字符串所以如果我有一个名为John Mathews的客户,他们可以输入jo或joh或john来找到它但是当他们输入john ma或john mat时它会返回零行。类似地,当他们键入john 4455667(其中4455667是conatct详细信息)。

我该如何解决?

SELECT DISTINCT customers.customer_id, CONCAT(IFNULL(titles.title_name, ""), " " , customers.first_name, " ", customers.middle_name, " ", customers.last_name) AS customer_name, MAX(DATE(advance_orders.delivery_date)) AS last_order
FROM customers
LEFT JOIN titles ON titles.title_id = customers.title
LEFT JOIN companies ON companies.company_id = customers.company
LEFT JOIN job_titles ON job_titles.job_title_id = customers.job_title
LEFT JOIN customers_contact ON customers_contact.customer_id = customers.customer_id
LEFT JOIN advance_orders ON advance_orders.customer_id = customers.customer_id
WHERE first_name LIKE CONCAT('%', param_find ,'%')
OR middle_name LIKE CONCAT('%', param_find ,'%')
OR last_name LIKE CONCAT('%', param_find ,'%')
OR customers_contact.contact_details LIKE CONCAT('%', param_find ,'%')
OR companies.company_name LIKE CONCAT('%', param_find ,'%')
OR job_titles.job_title_name LIKE CONCAT('%', param_find ,'%')
GROUP BY customers.customer_id
ORDER BY customer_name;

1 个答案:

答案 0 :(得分:0)

而不是:

WHERE first_name LIKE CONCAT('%', param_find ,'%')
OR middle_name LIKE CONCAT('%', param_find ,'%')
OR last_name LIKE CONCAT('%', param_find ,'%')

尝试:

WHERE CONCAT(first_name, ' ', last_name) LIKE CONCAT('%', param_find ,'%')
OR CONCAT(first_name, ' ',middle_name, ' ', last_name) LIKE CONCAT('%', param_find ,'%')

当然,您可以将逻辑扩展到另一个OR:

OR customers_contact.contact_details LIKE CONCAT('%', param_find ,'%')
OR companies.company_name LIKE CONCAT('%', param_find ,'%')
OR job_titles.job_title_name LIKE CONCAT('%', param_find ,'%')

如果你需要。

此致