MySQL在两行中查找全名

时间:2012-04-23 21:10:01

标签: mysql

我有一个MySQL表,我正试图用他的全名找到一个人。问题是名字和姓氏存储在表格中的两个单独的行上,如下所示:

+-----------------+-------------+-------------+--------------+
| submit_time     | form_name   | field_name  | field_value  |
+-----------------+-------------+-------------+--------------+
| 1323463601.0947 | Online Form | firstname   | Paulo        |
| 1323463601.0947 | Online Form | lastname    | Hill         |
+-----------------+-------------+-------------+--------------+

如何构建一个通过搜索Paulo Hill获得单个结果(如果可能)的查询?

此外,submit_time列对于两行应具有相同的值 - 这将是表中唯一的一列值。

4 个答案:

答案 0 :(得分:4)

您可以使用自我加入:

SELECT t1.submit_time, t1.field_value, t2.field_value
FROM your_table t1
INNER JOIN your_table t2 ON t2.submit_time = t1.submit_time
WHERE t1.field_name = 'firstname'
AND t1.field_value = 'Paulo'
AND t2.field_name = 'lastname'
AND t2.field_value = 'Hill'

答案 1 :(得分:2)

假设'paulo hill'是一个搜索查询:

    SELECT t1.*,
           t2.field_value
      FROM tbl t1
INNER JOIN tbl t2 ON t1.submit_time = t2.submit_time
       AND t2.field_name = 'lastname'
     WHERE t1.field_name = 'firstname'
       AND t1.field_value || ' ' || t2.field_value = 'paulo hill'

注意:此解决方案对搜索查询中的名字和姓氏之间的空格量敏感

答案 2 :(得分:1)

试试这个:

SELECT * FROM (
  SELECT submit_time, group_concat(field_value SEPARATOR  ' ')  AS fullname
  FROM TABLE_NAME
  GROUP BY `submit_time`
) AS innertable
WHERE fullname='Paulo Hill'

答案 3 :(得分:0)

如果您知道订单,则可以使用GROUP_CONCAT

SELECT GROUP_CONCAT(field_value SEPARATOR ' ') 
FROM tab
GROUP BY submit_time
HAVING GROUP_CONCAT(field_value ORDER BY field_id ASC) LIKE '%Paulo,Hill%'