MySQL高级选择

MySQL高级选择,mysql,select,Mysql,Select,我使用一个简单的var/val表来存储我网站的用户信息。用户的格式如下所示: uid = 1 fname = محمد مهدی lname = عرب dep = 5 bday = 15 bmonth = 11 byear = 1368 cphone = 09399309399 phone = 03412815580 email = m.arab@noavaranit.com col = B0DAFF credit = 0 username = m.arab password = iamnoo

我使用一个简单的var/val表来存储我网站的用户信息。用户的格式如下所示:

uid = 1
fname = محمد مهدی
lname = عرب
dep = 5
bday = 15
bmonth = 11
byear = 1368
cphone = 09399309399
phone = 03412815580
email = m.arab@noavaranit.com
col = B0DAFF
credit = 0
username = m.arab
password = iamnoone
lastlogin = 1406173285
admin = 1
per = 1,1
active = 1
id = 1
select t.*
from yourTable as t
     inner join (
         select sid from yourTable where var='admin' and val=1
     ) as t_admin on t.sid = t_admin.sid
     inner join (
         select sid from yourTable where var='dep' and val=x -- Replace the x with the appropriate value
     ) as t_dep on t.sid = t_dep.sid
请注意,所有用户都定义了一个sid,该sid在每个mysql行中都可用。因此,上面的每一行尽管在em中有一个var和val,但它们也有一个sid col,这是一个为每个用户延迟的数字

我需要选择一个用户,其中有两个行值。例如:

我需要找到一个用户,它的'dep'是x,它的'admin'也等于1


澄清:

您在上面解释用户ATT时看到的每一行实际上都是我sql中的一行“每一行都是一行”

为了进一步澄清,我将向你们提出一个问题

id     sid      var       val        date
185    12       email     xxx@xxx.xx `mysql timestamp`
283    92       name      Edward     `mysql timestamp`

一个简单的
,其中
听起来像是解决方案:

select *
from yourTable
where dep=x -- Substitute the x with the value you need
  and admin = 1
您的数据示例告诉我,
x
必须是一个整数。。。当然,如果它是一个字符串,请用引号括起该值:
'x'


您更新的问题清楚地说明了问题所在。。。我想我有一个解决办法(也许不太好,但会奏效)

所以,它应该是这样的:

uid = 1
fname = محمد مهدی
lname = عرب
dep = 5
bday = 15
bmonth = 11
byear = 1368
cphone = 09399309399
phone = 03412815580
email = m.arab@noavaranit.com
col = B0DAFF
credit = 0
username = m.arab
password = iamnoone
lastlogin = 1406173285
admin = 1
per = 1,1
active = 1
id = 1
select t.*
from yourTable as t
     inner join (
         select sid from yourTable where var='admin' and val=1
     ) as t_admin on t.sid = t_admin.sid
     inner join (
         select sid from yourTable where var='dep' and val=x -- Replace the x with the appropriate value
     ) as t_dep on t.sid = t_dep.sid
另一个解决方案是手动创建“透视表”:

我假设没有一个用户可以为每个var拥有多个条目(即tuple
sid,var
是唯一的)

有时,这种“透视表”的速度可能非常慢,因此创建一个临时表,添加适当的索引,然后过滤所需的数据是值得的:

drop table if exists temp_aTable;
create temporary table temp_aTable
    select sid,
        max(case var when 'dep' then val end) as dep,
        max(case var when 'admin' then val end) as admin
    from yourTable
    where var in ('dep', 'admin')
    group by sid;
alter table temp_aTable
    add primary key (sid),
    add index d(dep),
    add index a(admin);
select *
from temp_aTable
where dep=x
  and admin=1;

请记住:临时表仅对创建它们的连接可见,并且在连接关闭时将被删除。

需要帮助,请尽快!现在它更有意义了。。。给我一分钟编辑我的答案!非常感谢,我真的很绝望。我没那么笨。我知道如何选择基本查询
dep
col和
admin
col不存在。“我的列是id sid var val date”“admin”和“dep”属性用于var列,它们的值在val列中。立即获取?如何知道每个用户的
var
值是什么?您的表结构是否类似于
uid、variable、value
?我更喜欢“pivot”方法谢谢!这对我真的很有帮助。我将使用枢轴方法!我真的很感谢你教我关于“支点”的知识,我知道这样的东西是存在的,因为我不知道如何使用它。谢谢,救了我一天;)