MySQL高级选择

时间:2014-07-24 05:18:37

标签: 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 = iamnoone
lastlogin = 1406173285
admin = 1
per = 1,1
active = 1
id = 1

请注意,所有用户都使用sid定义,该sid在每个mysql行中都可用。所以上面的每一行尽管有一个var和val,但他们也有一个sid col,这是一个推断每个用户的数字。

我需要选择一个具有2个这些行值的用户。例如:

我需要找到一个用户,其'dep'是x,而且'admin'等于1;


澄清:

你在上面看到的解释用户注册的每一行实际上都是我的SQL中的一行“每一行都是行”;

为了澄清更多,我会画一行

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

1 个答案:

答案 0 :(得分:1)

一个简单的where听起来像解决方案:

select *
from yourTable
where dep=x -- Substitute the x with the value you need
  and admin = 1

您的数据示例告诉我x必须是整数...但当然,如果它是一个字符串,请将值括在引号中:'x'


你的更新问题明确了问题是什么......我认为我有一个解决方案(也许它不漂亮,但它会起作用)

所以,它会是这样的:

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

另一种解决方案是手工创建“数据透视表”:

select *
from 
    (
        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
    ) as a
where dep = x -- Same comment as above
  and admin = 1

我假设没有一个用户可以为每个var创建多个条目(也就是说,元组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;

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