如何获取表中的行?

时间:2013-04-22 04:40:01

标签: php mysql sql

我有一个包含以下列的表:

User_id, Key, Value

在此表中记录如下:

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

我想获取特定名字和姓氏对的user_id。我如何获得查询来执行此操作?例如,如果我查询Bob Jones

,我想获得1

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分:0)

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

2)获得具有相同ID且第一个= 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名称,则可以将其替换为

   SUBSTRING_INDEX(name,' ',1)

   SUBSTRING_INDEX(name,' ',2)