在mysql查询中获取匹配的列值

时间:2016-01-25 12:21:40

标签: php mysql sql-like

我有一个像这样的表结构:

   -----------------------------------------------------------------------
   ID | Scifi Name       |       Hospital Code       |     Layman Language    |
     1 | Hysoc           |       CBC                 |  torems
    2  | Loreim          |       HCI                 |   Loreims
    -----------------------------------------------------------------------

我正在尝试匹配值,而像这样查询:

"SELECT * FROM wp_vhh4zdnv0r_disease WHERE scifi_name like '%".$_GET['term']."%' OR hospital_code like '%".$_GET['term']."%' OR layman_language like '%".$_GET['term']."%'";

查询工作正常但我正在尝试获取匹配值的字段。如果term ='cbc'中存在cbcHospital code它只返回医院代码?我应该如何实现这一点。可能是PHP代码可以帮助,但我不知道如何得到那个谢谢

2 个答案:

答案 0 :(得分:0)

你可以像这样使用case语句:

$sql= "SELECT CASE WHEN scifi_name like '%".$_GET['term']."%' THEN scifi_name 
WHEN phospital_code like '%".$_GET['term']."%' THEN phospital_code
WHEN layman_language like '%".$_GET['term']."%' THEN layman_language 
END FROM wp_vhh4zdnv0r_disease";

答案 1 :(得分:0)

您可以使用UNION。另外,不要忘记使用mysqli_real_escape_string()或类似函数来转义用户输入。

SELECT scifi_name FROM wp_vhh4zdnv0r_disease WHERE scifi_name like '%".$_GET['term']."%' UNION SELECT hospital_code FROM wp_vhh4zdnv0r_disease WHERE hospital_code like '%".$_GET['term']."%' UNION SELECT layman_language FROM wp_vhh4zdnv0r_disease WHERE layman_language like '%".$_GET['term']."%'"