mysql获取包含3个表的表的最后2条记录

时间:2016-09-15 13:37:52

标签: php mysql

我有3个mysql表(order,camp,user)作为下面的值,

ALTER TABLE IF EXISTS custom_table 
  DROP CONSTRAINT IF EXISTS fk_states_list;

我希望结果如下:

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

来自order_table的每个用户的最后2条记录今天订单 by orderDate

我想加入这些表格,以便从 camp_table camp_table uname uname 来自 order_table 的strong>消息。 今天订单 by orderDate 感谢

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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