我需要在MySQL表中实现搜索。它将数据存储在不同的行中,因此我使用MySQL中的数据透视功能来获取数据 当我只需要搜索一个值时,它运行良好(表格结构如下)。
| id | lead_id | form_id | field_number | value |
===================================================
| 1 | 12 | 12 | 2.3 | John |
| 2 | 12 | 12 | 4.3 | Dublin |
| 3 | 13 | 12 | 2.3 | Sam |
| 4 | 13 | 12 | 4.3 | Cork |
| 5 | 16 | 14 | 5 | 897894 |
| 16 | 16 | 16 | 7 | test |
| 17 | 12 | 12 | 4.4 | Ireland |
| 18 | 12 | 12 | 7 | 8899899 |
| 19 | 13 | 12 | 4.4 | USA |
| 20 | 13 | 12 | 7 | 0909902 |
--------------------------------------------------
我用来搜索的初始查询如下。当我只需要通过'name'
进行搜索时,它运行良好SELECT lead_id,
MAX( IF( ROUND( `field_number` , 1 ) = '2.3', value, 0 ) ) AS "Name",
MAX( IF( ROUND( `field_number` , 1 ) = '4.3', value, 0 ) ) AS "City",
MAX( IF( ROUND( `field_number` , 1 ) = '4.4', value, 0 ) ) AS "State",
MAX( IF( ROUND( `field_number` , 1 ) = '7', value, 0 ) ) AS "SSnumber"
FROM details
WHERE lead_id IN
(
SELECT DISTINCT lead_id
FROM details
WHERE
(round(`field_number`,1) = '2.3' AND `value` LIKE '%s%')
AND form_id = 12
)
GROUP BY `lead_id`
现在我需要实现一个过滤器来按城市,州和密码进行搜索 所以我需要对此查询进行更改,但我没有让它正常工作 我需要为搜索添加一个AND条件,按城市,州和密码进行过滤,就像这样。
SELECT lead_id,
MAX( IF( ROUND( `field_number` , 1 ) = '2.3', value, 0 ) ) AS "Name",
MAX( IF( ROUND( `field_number` , 1 ) = '4.3', value, 0 ) ) AS "City",
MAX( IF( ROUND( `field_number` , 1 ) = '4.4', value, 0 ) ) AS "State",
MAX( IF( ROUND( `field_number` , 1 ) = '7', value, 0 ) ) AS "SSnumber"
FROM details
WHERE lead_id IN
(
SELECT DISTINCT lead_id
FROM details
WHERE
(
(round(`field_number`,1) = '2.3' AND `value` LIKE '%s%') AND
(round(`field_number`,1) = '4.3' AND `value` LIKE '%d%') AND
(round(`field_number`,1) = '4.4' AND `value` LIKE '%r%') AND
)
AND form_id = 12
)
GROUP BY `lead_id`
这不能用作存储在不同行中的数据。能否请你给我一个排序方法。
答案 0 :(得分:2)
我不完全了解条件,但尝试使用子查询。例如 -
SELECT * FROM (
SELECT
lead_id,
MAX(IF(ROUND(field_number, 1) = '2.3', value, 0)) AS 'Name',
MAX(IF(ROUND(field_number, 1) = '4.3', value, 0)) AS 'City',
MAX(IF(ROUND(field_number, 1) = '4.4', value, 0)) AS 'State',
MAX(IF(ROUND(field_number, 1) = '7', value, 0)) AS 'SSnumber'
FROM details
WHERE form_id = 12
GROUP BY lead_id
) d
WHERE
Name LIKE '%s%' AND City LIKE '%d%' AND State LIKE '%r%';