mysql select from table 使用特定列的非重复计数
mysql select from table using the distinct count of specific column
我有一个包含两列的 table,dept_id 和 loc_id 如下:
+----------+--------+
| dept_id | loc_id |
+----------+--------+
| 1 | 1 |
| 2 | 1 |
| 2 | 2 |
| 3 | 1 |
| 3 | 2 |
| 3 | 3 |
| 3 | 4 |
| 3 | 5 |
+----------+--------+
我想 select 前两个 'dept_ids' 动态而不使用 "IN" 因为我不知道前两个 'dept_ids',然后 select 接下来的两个 'dept_ids' .. 等等,所以如果我 select 前两个:
它应该检索这个
+----------+--------+
| dept_id | loc_id |
+----------+--------+
| 1 | 1 |
| 2 | 1 |
| 2 | 2 |
+----------+--------+
这可能吗?
我正在使用 MySQL 数据库,使用 PHP 作为编程语言。
SQL 没有 "first" 行的概念,除非另一列指定了排序。如果你只有一个 table,你可以有效地做你想做的事情:
select t.*
from table t join
(select dept_id
from table t
group by dept_id
order by dept_id
limit 0, 2
) td
on t.dept_id = td.dept_id;
您只需将 0
更改为 2
,然后 4
,依此类推。
更常见的是,我希望您有 Departments
table。如果是:
select t.*
from table t join
(select dept_id
from Departments d
order by dept_id
limit 0, 2
) td
on t.dept_id = td.dept_id;
无论哪种情况,您都需要 dept_id
上的索引以提高性能。
我有一个包含两列的 table,dept_id 和 loc_id 如下:
+----------+--------+
| dept_id | loc_id |
+----------+--------+
| 1 | 1 |
| 2 | 1 |
| 2 | 2 |
| 3 | 1 |
| 3 | 2 |
| 3 | 3 |
| 3 | 4 |
| 3 | 5 |
+----------+--------+
我想 select 前两个 'dept_ids' 动态而不使用 "IN" 因为我不知道前两个 'dept_ids',然后 select 接下来的两个 'dept_ids' .. 等等,所以如果我 select 前两个:
它应该检索这个+----------+--------+
| dept_id | loc_id |
+----------+--------+
| 1 | 1 |
| 2 | 1 |
| 2 | 2 |
+----------+--------+
这可能吗?
我正在使用 MySQL 数据库,使用 PHP 作为编程语言。
SQL 没有 "first" 行的概念,除非另一列指定了排序。如果你只有一个 table,你可以有效地做你想做的事情:
select t.*
from table t join
(select dept_id
from table t
group by dept_id
order by dept_id
limit 0, 2
) td
on t.dept_id = td.dept_id;
您只需将 0
更改为 2
,然后 4
,依此类推。
更常见的是,我希望您有 Departments
table。如果是:
select t.*
from table t join
(select dept_id
from Departments d
order by dept_id
limit 0, 2
) td
on t.dept_id = td.dept_id;
无论哪种情况,您都需要 dept_id
上的索引以提高性能。