我正在尝试获取usertype 1
或usertype 3
类型的所有用户。
我想我可以使用连接来实现,但我想要一些没有连接的东西。
以下是我的尝试:
$users = User::model()->findAllBySql("SELECT * FROM user WHERE (usertype = 3 and usertype = 1)");
我正在使用Yii,但它应该是相同的SQL原则。
用户(id,username,usertype,name);
usertype
是1,2或3。
答案 0 :(得分:1)
您可以这样使用CActiveRecord findAll()
方法:
$users = User::model()->findAll(array('condition'=>'usertype = 3 OR usertype = 2'));
答案 1 :(得分:0)
您需要熟悉SQL WHERE子句
http://www.w3schools.com/sql/sql_where.asp
特别是@Gordon指出," IN"节
的替代地强> 的
如果询问是找到2型和2型的用户。 3然后你可以尝试
select distinct(id, username, name) from user
where usertype = 2
AND id in (select id from user where usertype = 3)
然而,假设您的PK不是您的PK,那么您的PK是id&的组合。用户类型
使用示例表的更多信息以及您希望根据数据从查询中获得的内容将澄清问题
答案 2 :(得分:0)
我过分思考这个问题。归功于戈登·林诺夫,他说or
但我被蒙蔽了所以我无法理解。
以下是解决方案:
$users = User::model()->findAllBySql("SELECT * FROM user WHERE (usertype = 3 or usertype = 1)");
之前没有用,因为没有用户使用类型1和usertype 3.它是另一个or
。
答案 3 :(得分:0)
最后的查询应该能够得到你想要的东西。其余的就是这个例子。
drop schema example;
create schema example;
use example;
create table user(
user_id int primary key,
name varchar(64)
);
create table type(
type_id int primary key,
type_name varchar(64)
);
create table user_type (
user_id int,
type_id int,
foreign key(user_id) references user(user_id),
foreign key(type_id) references type(type_id)
);
insert into user values (1, 'John');
insert into user values (2, 'Paul');
insert into user values (3, 'George');
insert into user values (4, 'Ringo');
insert into type values (10, 'Guitar');
insert into type values (20, 'Bass');
insert into type values (30, 'Drums');
insert into type values (40, 'Vocals');
insert into type values (50, 'Sitar');
insert into user_type values (1, 10);
insert into user_type values (1, 40);
insert into user_type values (2, 20);
insert into user_type values (2, 40);
insert into user_type values (3, 10);
insert into user_type values (3, 40);
insert into user_type values (3, 50);
insert into user_type values (4, 30);
insert into user_type values (4, 40);
select
u.*
from
user u
join user_type guitar on u.user_id = guitar.user_id and guitar.type_id = 10
join user_type sitar on u.user_id = sitar.user_id and sitar.type_id = 50
;
编辑:这是在MySql中完成的。此查询的结果集是单个记录:George是唯一匹配吉他和西塔琴两种类型的用户。