我有两个表用户表和书表。
user_id
1
2
3
4
5
book
user_id book_id
1 1
2 2
4 5
我想从用户表中那些不存在书表的记录。我该怎么做?我试过这段代码,但还有其他有效的方法吗?
$cri_user = new CDbCriteria;
$cri_user->select = "t.user_id";
$cri_user->condition = "t.user_id NOT IN (select tu.user_id from books as tu group by tu.user_id)";
$model_user = User::model()->findAll($user);
如果我以mysql格式获得解决方案,我可以将其转换为yii。
答案 0 :(得分:2)
还有一些方法可以做同样的事情:
方法1:
$sql = "select t.* from user t left join book b on b.user_id = t.user_id where b.user_id is null";
$records = Yii::app()->db->createCommand($sql)->queryAll();
print_r($records);
方法2:
$records = Yii::app()->db->createCommand()
->select('t.*')
->from('user t')
->leftJoin('book b', 'b.user_id = t.user_id')
->where('b.user_id is null')
->queryAll();
print_r($records);
答案 1 :(得分:1)
你可以编写如下内容,
SELECT USER_ID FROM USER
WHERE NOT EXISTS (SELECT 1 FROM BOOKS
WHERE USER.USER_ID = BOOKS.USER_ID)