douchao9899 2013-11-28 08:13
浏览 188
已采纳

需要在一个字段Mysql中搜索两个值

I need search for two values in the same field.

╔════╦════════════╦══════════════╗
║ ID ║ Meta_key   ║ Meta_value   ║
╠════╬════════════╬══════════════╣
║  1 ║ first_name ║    pritesh   ║
║  2 ║ last_name  ║    mahajan   ║
║  3 ║ first_name ║    ritesh    ║
║  4 ║ last_name  ║    jain      ║
║  5 ║ first_name ║    john      ║
║  6 ║ last_name  ║    a         ║
║  7 ║ first_name ║    Mambo     ║
║  8 ║ last_name  ║    Nombo     ║
╚════╩════════════╩══════════════╝  

This is my table and I want to search all the first names and last names. Below is my query but this does not return what I want.

SELECT * 
FROM `wp_usermeta` 
WHERE `meta_key` = 'last_name' 
  AND `meta_value` LIKE  '%mahajan%' 
  AND `meta_key` = 'first_name' 
  AND `meta_value` LIKE  '%a%'; 
  • 写回答

4条回答 默认 最新

  • dsam70528 2013-11-28 09:51
    关注

    Here you go

    SQL Fiddle

    Query:

    SELECT first_name, last_name
    FROM 
      (
        (
          SELECT meta_value AS first_name, id AS a_id 
          FROM wp_usermeta 
          WHERE meta_name = 'first_name'
        ) as a
      )
    JOIN
      (
        (
          SELECT meta_value AS last_name, id AS b_id 
          FROM wp_usermeta 
          WHERE meta_name = 'last_name'
        ) as b
      )
    WHERE a_id = b_id-1
    

    Results:

    | FIRST_NAME | LAST_NAME |
    |------------|-----------|
    |    pritesh |   mahajan |
    |     ritesh |      jain |
    |       john |         a |
    |      Mambo |     Nombo |
    

    With this, you can easily search using the two virtual columns first_name and last_name. You just need to add additional conditions to the WHERE clause. something like this:

      WHERE a_id = b_id-1
      AND first_name LIKE "%tesh%"
      AND last_name LIKE "%jai%"
    

    will produce

    | FIRST_NAME | LAST_NAME |
    |------------|-----------|
    |     ritesh |      jain |
    

    NOTE

    The big assumption I have made here (based on your sample data) is that the related first_name and last_name are always going to have successive id's. (two successive records in the table).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧