[英]MySQL How to select multiple rows with WHERE multiple columns on the same table?
我想 select room_id
基于列user_id
和del
room_id | 用户身份 | 德尔 |
---|---|---|
1个 | 23 | 0 |
1个 | 45 | 0 |
1个 | 56 | 1个 |
25 | 23 | 0 |
25 | 45 | 0 |
25 | 56 | 0 |
这是我的桌子的一个例子,我想要 select room_id WHERE:
"user_id = 23 AND del = 0" (del of the row where user_id=23)
和
"user_id = 45 AND del = 0" (del of the row where user_id=45)
和
"user_id = 56 AND del = 0" (del of the row where user_id=56)
查询应仅返回room_id = 25
如何使用 PHP 或 CodeIgniter 实现此目的?
我试过使用它但它不起作用:
$this->db->select()
->from('table')
->where(['user_id' => 23, 'del' => 0])
->where(['user_id' => 45, 'del' => 0])
->where(['user_id' => 56, 'del' => 0])
->get()->result_array();
*注意:当我尝试在同一个表上使用连接表时它起作用了,但是当我有 10 个user_id
(连接同一个表 10 次)时,查询运行速度非常慢(因为它是一个大表,几乎有接近一百万行).
先感谢您。
使用where
子句过滤匹配的行,然后对结果进行分组并添加 having 子句:
SELECT room_id
FROM t
WHERE (user_id = 23 AND del = 0)
OR (user_id = 45 AND del = 0)
OR (user_id = 56 AND del = 0)
GROUP BY room_id
HAVING COUNT(*) = 3 -- there are three rows with matching condition for that room
你可以这样试试
SELECT room_id
FROM table
WHERE user_id = 23 AND del = 0 AND user_id = 45 AND del = 0 AND user_id = 56 AND del = 0;
然后查询可能看起来像这样
$this->db->select('room_id')
->from('table')
->where(['user_id' => 23, 'del' => 0])
->orWhere(['user_id' => 45, 'del' => 0])
->orWhere(['user_id' => 56, 'del' => 0])
->get()->result_array();
您可以将所有user_id
放在括号中:
SELECT room_id
FROM table
WHERE (user_id = 23 OR user_id = 45 OR user_id = 56) AND del = 0;
或者您可以使用WHERE IN
子句:
SELECT room_id
FROM table
WHERE user_id IN (23, 45, 56) AND del = 0;
“user_id = 23 AND del = 0”也会将房间 ID 1 添加到结果集中。 在 where 子句中添加 room_id = 25 的条件。
一种更简单的方法是:
SELECT room_id
FROM table_tbl
WHERE user_id in (23,45,56) AND del = 0
GROUP BY room_id
HAVING COUNT(*) = 3 ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.