使用3个表格从表格中获取最后2条记录的MySQL查询

5

我有3个mysql表(order,camp和user),其值如下:

order_table
ID    camp_id       orderDate       message
1       1           2015-01-01      ok
2       1           2015-02-01      ok
3       2           2015-03-01      not ok
4       3           2015-01-01      not ok
5       1           2015-04-01      not ok
6       2           2015-01-01      ok
7       3           2015-07-01      not ok

camp_table
camp_id camp_uid     camp name
1       10             first camp
2       11             second camp
3       12             third camp
4       10             forth camp

user_table
uid    uname
10      abc
11      xyz
12      wrt

我希望你能把结果呈现如下:

以下是需要翻译的内容:

uname,camp name,message

针对每个用户,从订单表中获取今天的最后2条记录,按照订单日期排序。

我希望连接这些表格,以便从用户表中获取“用户名”,从营地表中获取“营地名称”,并从订单表中获取“消息”。 按照订单日期,以今天的顺序排序。 谢谢。


请编辑并详细说明您的问题。 - FluxCoder
你想从订单表中仅获取最后2条记录,并且你想要使用连接操作吗? - Punit Gajjar
请参见http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query。 - Strawberry
3个回答

3
Select
ct.camp_name,
ut.uname,
ot.message FROM order_table as ot
LEFT JOIN camp_table as ct on ot.camp_id = ct.camp_id
LEFT JOIN user_table as ut on ct.camp_uid = ut.uid
order by ot.id desc
limit 2

感谢回复。不是我想要的,我想要每个客户的两条记录,但是只显示今天的日期。这只显示了最后两条记录。 - Mr.SH

2
SELECT
    u.uname,
    ct.camp_name,
    ot.message
FROM
    (
        SELECT
            *
        FROM
            order_table o1
        WHERE
            (
                SELECT
                    COUNT(*)
                FROM
                    order_table o2
                WHERE
                    o1.camp_id = o2.camp_id
                AND o2.ID >= o1.ID
            ) <= 2
    ) ot
INNER JOIN camp_table ct ON ct.camp_id = ot.camp_id
INNER JOIN user_table u ON ct.camp_uid = u.uid
ORDER BY
    u.uname

你好,这是无尽的查询并且 MySQL 卡住了。 - Mr.SH
它在我的系统上运行,使用你问题中的数据库值。 - user5189304

1
按日期排序并连接两个表。
  Select t1.camp_name, t2.uname,t3.message FROM order_table as t3
    LEFT JOIN camp_table as t1 on t3.camp_id = t1.camp_id
    LEFT JOIN user_table as t2 on t1.camp_uid = t2.uid
    order by t3.orderDate desc
    limit 2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接