其中来自另一个 select 的列结果有限制 (mysql/mariadb)
where column in from another select results with limit (mysql/mariadb)
当我 运行 这个查询 returns 表 2select 中存在其 ID 的所有行
SELECT * FROM table1 WHERE id in (
SELECT id FROM table2 where name ='aaa'
)
但是当我在第二个 select 之间添加 limit 或 between 时:
SELECT * FROM table1 WHERE id in (
SELECT id FROM table2 where name ='aaa' limit 4
)
returns 这个错误:
This version of MariaDB doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
您可以使用 ROW_NUMBER()
等分析函数来 return 子查询中的一行。我想,这样就不会出现像引发太多行问题这样的问题了:
SELECT * FROM
(
SELECT t1.*,
ROW_NUMBER() OVER (ORDER BY t2.id DESC) AS rn
FROM table1 t1
JOIN table2 t2 ON t2.id = t1.id
WHERE t2.name ='aaa'
) t
WHERE rn = 1
P.S.: 顺便说一下,id 列应该是表的主键,不是吗?
Update(根据您在评论中的需要)考虑使用:
SELECT * FROM
(
SELECT j.*,
ROW_NUMBER() OVER (ORDER BY j.id DESC) AS rn2
FROM job_forum j
CROSS JOIN
( SELECT t.*,
ROW_NUMBER() OVER (PARTITION BY t2.id ORDER BY t2.id DESC) AS rn1
FROM table2 t2
WHERE t2.name ='aaa'
AND t2.id = j.id ) t2
WHERE rn1 = 1
) jj
WHERE rn2 <= 10
您使用的 LIMIT
没有 ORDER BY
。通常不推荐这样做,因为 returns 一组任意的行 - 并且这些行可以从一次执行更改为另一次执行。
您可以将其转换为 JOIN
——幸运的是。如果id
在table2
中不重复:
SELECT t1.*
FROM table1 t1 JOIN
(SELECT t2.id
FROM table2 t2
WHERE t2.name = 'aaa'
LIMIT 4
) t2
USING (id);
如果id
可以在table2
中复制,那么:
SELECT t1.*
FROM table1 t1 JOIN
(SELECT DISTINCT t2.id
FROM table2 t2
WHERE t2.name = 'aaa'
LIMIT 4
) t2
USING (id);
另一种有趣的方式是使用 LIMIT
:
SELECT t1.*
FROM table1 t1
WHERE id <= ANY (SELECT t2.id
FROM table2
WHERE t2.name = 'aaa'
ORDER BY t2.id
LIMIT 1 OFFSET 3
);
LIMIT
允许在标量子查询中使用。
当我 运行 这个查询 returns 表 2select 中存在其 ID 的所有行
SELECT * FROM table1 WHERE id in (
SELECT id FROM table2 where name ='aaa'
)
但是当我在第二个 select 之间添加 limit 或 between 时:
SELECT * FROM table1 WHERE id in (
SELECT id FROM table2 where name ='aaa' limit 4
)
returns 这个错误:
This version of MariaDB doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
您可以使用 ROW_NUMBER()
等分析函数来 return 子查询中的一行。我想,这样就不会出现像引发太多行问题这样的问题了:
SELECT * FROM
(
SELECT t1.*,
ROW_NUMBER() OVER (ORDER BY t2.id DESC) AS rn
FROM table1 t1
JOIN table2 t2 ON t2.id = t1.id
WHERE t2.name ='aaa'
) t
WHERE rn = 1
P.S.: 顺便说一下,id 列应该是表的主键,不是吗?
Update(根据您在评论中的需要)考虑使用:
SELECT * FROM
(
SELECT j.*,
ROW_NUMBER() OVER (ORDER BY j.id DESC) AS rn2
FROM job_forum j
CROSS JOIN
( SELECT t.*,
ROW_NUMBER() OVER (PARTITION BY t2.id ORDER BY t2.id DESC) AS rn1
FROM table2 t2
WHERE t2.name ='aaa'
AND t2.id = j.id ) t2
WHERE rn1 = 1
) jj
WHERE rn2 <= 10
您使用的 LIMIT
没有 ORDER BY
。通常不推荐这样做,因为 returns 一组任意的行 - 并且这些行可以从一次执行更改为另一次执行。
您可以将其转换为 JOIN
——幸运的是。如果id
在table2
中不重复:
SELECT t1.*
FROM table1 t1 JOIN
(SELECT t2.id
FROM table2 t2
WHERE t2.name = 'aaa'
LIMIT 4
) t2
USING (id);
如果id
可以在table2
中复制,那么:
SELECT t1.*
FROM table1 t1 JOIN
(SELECT DISTINCT t2.id
FROM table2 t2
WHERE t2.name = 'aaa'
LIMIT 4
) t2
USING (id);
另一种有趣的方式是使用 LIMIT
:
SELECT t1.*
FROM table1 t1
WHERE id <= ANY (SELECT t2.id
FROM table2
WHERE t2.name = 'aaa'
ORDER BY t2.id
LIMIT 1 OFFSET 3
);
LIMIT
允许在标量子查询中使用。