用于检索最后一条记录的SQL查询

时间:2014-04-24 17:14:39

标签: sql

我有与另一个表article_has_type

相关的表格文章

文章表的结构是

    CREATE TABLE `articles` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `titre` VARCHAR(255) NULL DEFAULT NULL,
    `description` TEXT NULL,
)

表article_has_type的结构是

CREATE TABLE `arhastypes` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `article_id` INT(11) NULL DEFAULT NULL,
    `type_id` INT(11) NULL DEFAULT NULL,
)

我想将最后一篇文章添加到每种类型中。

谢谢。

7 个答案:

答案 0 :(得分:3)

由于id列为AUTO INCREMENT,您可以这样做:

获取articles中的最后一条记录:

SELECT * FROM articles WHERE id=(SELECT MAX(id) FROM articles)

要获取每种类型arhastypes的最后记录的详细信息:

SELECT * FROM arhastypes WHERE id IN 
            (SELECT MAX(id) FROM arhastypes
             GROUP BY type_id)

修改

要从两个表中选择记录,您可以执行以下操作:

SELECT ART.id,ART.titre,ART.description,ARH.id as arhastypes_id,ARH.type_id
FROM arhastypes ARH JOIN
     articles ART ON ARH.article_id=ART.id
WHERE ARH.id IN (SELECT MAX(id) FROM arhastypes
                 GROUP BY type_id)

答案 1 :(得分:1)

正在寻找这个吗?

Select * from articles where id in (select max(id) from articles)
Select * from arhastypes where id in (select max(id) from arhastypes)

答案 2 :(得分:1)

Select * from articles where id in 
(select max(arhastypes.article_id) from arhastypes where type_id=1)

答案 3 :(得分:0)

以下查询应该会为您提供添加到每种类型的最后一篇文章(假设id列为AUTO INCREMENT):

select arhastypes.type_id, articles.title, articles.description from articles join arhastypes on arhastypes.article_id = articles.id order by articles.id desc group by arhastypes.type_id

答案 4 :(得分:0)

尝试:

select top 1 from articles
order by ID desc

select top 1 from arhastypes
order by ID desc

答案 5 :(得分:0)

尝试这样的事情:

Select  A.*
From    Articles    A
Where   A.id In
(
    Select  Max(article_id)
    From    arhastypes
    Where   type_id = @type_id
)

要为每种类型添加最新文章到每种类型,您可以执行以下操作:

Select  T.type_id, A.*
From    Articles    A
Join    arhastypes  T On A.id = T.article_id
Where   A.id In
(
    Select  Max(article_id)
    From    arhastypes
    Group By type_id
)

答案 6 :(得分:0)

每次都有效:

Select  A.*
From    Articles    A
ORDER BY A.id DESC
LIMIT 1