【问题标题】:mysql get last 2 records of table with 3 tablesmysql 获取表的最后 2 条记录,其中包含 3 个表
【发布时间】:2016-09-15 13:37:52
【问题描述】:

我有 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

今天订单按orderDate

的order_table中每个用户的最后2条记录

我想加入这些表,以使 user_table 中的 unamecamp_table 中的 camp name 和 order_table 的strong>消息。 今天订单按订单日期 谢谢

【问题讨论】:

标签: php mysql


【解决方案1】:
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

【讨论】:

  • 感谢回复 不,这不是我想要的,我想要每个客户的 2 条记录,但今天的日期。这仅显示 2 条最后记录
【解决方案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卡住了
  • 它可以在我的系统上运行,并使用您问题中的数据库值。
【解决方案3】:

按日期排序并加入两个表。

  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

【讨论】:

    猜你喜欢
    • 2022-10-01
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多