Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何选择列中具有相同值的行,而不事先知道该值?_Mysql - Fatal编程技术网

Mysql 如何选择列中具有相同值的行,而不事先知道该值?

Mysql 如何选择列中具有相同值的行,而不事先知道该值?,mysql,Mysql,我有一张记录表 Table records(id, docId, title) 给定一个id,我想选择所有与该id相同或小于该id的行,这些行共享相同的docId。我事先不知道文件 以下是一些示例数据: insert into records (id, docId, title) values (1, 1, 'a'), (2, 1, 'b'), (3, 2, 'c'), (4, 1, 'd') 我可以用两个选择来做这件事,就像这样 select @docId := docId from re

我有一张记录表

Table records(id, docId, title)
给定一个id,我想选择所有与该id相同或小于该id的行,这些行共享相同的docId。我事先不知道文件

以下是一些示例数据:

insert into records (id, docId, title) values
(1, 1, 'a'),
(2, 1, 'b'),
(3, 2, 'c'),
(4, 1, 'd')
我可以用两个选择来做这件事,就像这样

select @docId := docId from records where id = 4;

select id, title from records where docId = @docId and id <= 4;

我想知道:是否可以在单个查询中执行此操作?

我不知道是否理解您的问题,但如果您只需要在一个查询中搜索记录,则subselect可能会帮助您

select r.id, r.title
from records r
where r.docId in (
    select r2.docId
    from records r2
    where r2.id = 4
)
and r.id <= 4

我希望我帮了忙。最好的威士忌。

您可以加入两个查询:

SELECT id, title
FROM   records a
JOIN   records b ON a.docId = b.docId AND a.id < b.id
WHERE  b.id = 4;

请发布样本数据和预期结果。
SELECT id, title
FROM   records a
JOIN   records b ON a.docId = b.docId AND a.id < b.id
WHERE  b.id = 4;