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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘