查询很困难。
我有一个名为project_slugs
的表,其中包含以下字段id, project_id, slug, created
。
我有一个主表projects
,其中包含各个字段。
通过projects.id
和project_slugs.project_id
存在外键关系。
project_slugs
可以为任何给定项目包含多个子段。
我想获得一个单一的结果,其中包含projects
表中的所有字段以及该项目的最近创建的 projects_slug.slug
。这可以通过WHERE projects_slug.slug = 'some-slug'
完成,其中“ some-slug”可能是也可能不是最近的。
我能够成功加入表格,但是我不确定如何合并上面的粗体逻辑。
这是我当前的查询:
SELECT projects.*, project_slugs.slug
FROM `project_slugs` LEFT JOIN
`projects`
ON project_slugs.project_id = projects.id
WHERE project_slugs.slug = 'some-slug'
插头:
项目:
预期的输入输出:
SELECT projects.*, project_slugs.slug
FROM `project_slugs` LEFT JOIN
`projects`
ON project_slugs.project_id = projects.id
WHERE project_slugs.slug = 'star-management-week-2015'
期望的输出将是您在最后一张图像中看到的结果+由slug
确定的最新的 project_slugs.created
值。给定 any project_slugs.slug
(新的或旧的)作为标识符。我什至不确定在sql中是否可行。逻辑在php中非常简单。
答案 0 :(得分:1)
您还应该将联接与子查询一起用于由project_id创建的最大组
SELECT projects.*,
project_slugs.slug
FROM projects
inner join (
select project_id, max(created) max_created
from project_slugs
group by project_id
) t on t.project_id = projects.id
inner join `project_slugs` ON project_slugs.project_id = projects.id
AND project_slugs.created = t.max_created
答案 1 :(得分:1)
我想您想要任何有问题的项目中的最新项目。如果是这样:
NSArray *services = @[[CBUUID UUIDWithString:@"180A"]];
_connectedPeripherals = [_btManager retrieveConnectedPeripheralsWithServices:services];
如果您实际上只希望最近的子段是指定的子段的项目,则在MySQL中,可以使用扩展的select p.*,
(select ps.slug
from project_slugs ps
where ps.project_id = p.id
order by ps.created desc
limit 1
) as most_recent_slug
from projects p
where exists (select 1
from project_slugs ps
where ps.project_id = p.id and
ps.slug = 'some-slug'
);
子句。将having
替换为:
where