显示最新记录和联接多个表

时间:2020-06-18 10:23:37

标签: mysql sql

我如何联接多个表并显示每个用户出售的物品,显示谁出售物品的最新记录 我需要这样的输出

销售者: 价格为“ 1000”的“ jon”项目“#1”“ book”

尝试:

SELECT uid , users.name AS uname, transact.transaction_id AS transacted INNER JOIN users on transaction_table.c_id=c_table.c_id


   User table
    --------------------------
    | uid | name |  timezone |
    --------------------------
    |  1  | jon  |  +1 gmt   |
    |  2  | mix  |  +2 gmt   |
    |  3  | vic  |  +1 gmt   |
    --------------------------


    transaction table
    -------------------------------
    | transaction_id | uid | c_id |
    -------------------------------
    | dafsf22sdfssgs | 2   |  1   |
    | 23425asda3afaa | 1   |  1   |
    -------------------------------


    C-table
    ------------------------
    | c_id | c_name | price |
    ------------------------
    |  1   | book   | 1000  |
    |  2   | comic  | 100   |
    |  3   | notes  | 10    |
    -------------------------

1 个答案:

答案 0 :(得分:0)

如果您想按商品名称分组并获得总计

select u.name,count(*) as count, c.c_name, c.price*count(*) as totalPrice from user u
inner join transaction t on u.uid=t.uid
inner join ctable c on c.c_id=t.c_id
group by c.c_name

如果您要查询所有交易

select u.name, c.c_name, c.price from user u
inner join transaction t on u.uid=t.uid
inner join ctable c on c.c_id=t.c_id

如果您只想返回上一笔交易信息

select u.name, c.c_name, c.price from user u
inner join transaction t on u.uid=t.uid
inner join ctable c on c.c_id=t.c_id
order by t.transaction_id desc limit 1

还有一件事。如果您的字段名称一致,则是更好的做法。