1

我有一个 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

4 回答 4

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'
于 2012-04-23T21:14:01.543 回答
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'

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

于 2012-04-23T21:12:51.043 回答
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'
于 2012-04-23T21:16:52.603 回答
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%'
于 2012-04-23T21:26:52.543 回答