0

I have a table with the following columns:

User_id, Key, Value

In this table are records such as:

1, "first name", "Bob"  
2, "first name", "Mike"  
1, "last name", "Jones"  
2, "last name", "Carter"

I want to get the user_id for a specific first and last name pair. How can I get a query to do this? For example, I want to get 1 if I query for Bob Jones

4

2 回答 2

0

将表连接到自身:

SELECT t1.User_id
FROM myTable t1
JOIN myTable t2 ON t1.User_Id = t2.UserId
WHERE t1.Key = 'first name' AND t2.Key = 'last name'
AND t1.Value = "Bob" AND t2.Value = "Jones"

或具有以下串联条件:

SELECT t1.User_id
FROM myTable t1
JOIN myTable t2 ON t1.User_Id = t2.UserId
WHERE t1.Key = 'first name' AND t2.Key = 'last name'
AND (t1.Value + ' ' + t2.Value) = "Bob Jones"
于 2013-04-22T04:43:20.910 回答
0

这里有 2 个任务 1) 得到不同值的名字和姓氏

2) 得到具有相同 id 和 first =your_first+ last=your_last 的行

简单查询将是:

 select user_id from tab1 
 where 
   key="first name" and value=your_first 
   and 
   user_id in (select  user_id from tab1 where key="last name" and value=your_last)

但我担心这会被mysql优化得不好

考虑到您的 user_id 有索引,最好的查询将是

select a.user_id from (
 select user_id from tab1 where key="first name" and value=your_first )
)a left join 
 (select  user_id from tab1 where key="last name" and value=your_last) as b
 on a.user_id=b.user_id where b.user_id is not null;

如果您无法在上层(php?)脚本中获得 your_first/your_last name,您可以将其替换为

   SUBSTRING_INDEX(name,' ',1)

   SUBSTRING_INDEX(name,' ',2)
于 2013-04-22T04:51:03.057 回答