具有max函数的SQL内连接由groub

时间:2017-08-06 16:39:52

标签: mysql wordpress

通过使用max函数使用内部联接和组有一些问题。  我的细节:  表库存

let carts = [];
for (let i = 0; i < len; i++) {
  let cart = {};
  cart.item_name = items[i].get("item_name");
  cart.quantity = items[i].get("quantity");
  cart.amount =  items[i].get("amount");
  cart.total = cart.amount * cart.quantity;
  cart.subtotal = cart.subtotal + cart.total;
  carts.push(cart);
 }
console.log(carts);

表wp_users(wordpress)

 site_ID  tank_number volume    times-tramp     ID  
  1      1         5000    06/08/2017 15:00      1
  1      1         4900    06/08/2017 15:01      2
  1      2         6000    06/08/2017 15:05      3
  1      3         4000    06/08/2017 15:05      4
  2      1         3000    06/08/2017 15:33      5
  2      2         2000    06/08/2017 15:34      6
  1      1         4800    06/08/2017 15:36      7
  1      2         5800    06/08/2017 16:00      8

现在,我在wordpress中使用wpdatatable插件,所以我想使用内部连接和tank_number组并使用times-strap数据更新 结果应该是:
当用户&#34; aaa&#34;登录然后ID将是1 希望展示的结果。

ID   Name
 1   aaa
 2   bbbb 

但是 我得到了这个结果:

site_ID  tank_number volume    times-tramp       
  1      1           4800    06/08/2017 15:36      
  1      2           5800    06/08/2017 16:00           
  1      3           4000    06/08/2017 15:05 

所以每个人都可以提醒我,所以我显示我的代码显示错误,因为我无法通过正确的语法sql加入2表。

此代码可以在没有内部联接的情况下工作

site_ID  tank_number volume    times-tramp 
1        1           5000    06/08/2017 15:00       
1        2           6000    06/08/2017 15:05       
1        3           4000    06/08/2017 15:05  

现在我尝试使用内连接但现在不能正常工作。

    select site_id, tank_product, volume, timestramp from inventory as t1
inner join (
    select tank_product as tank, max(timestramp) as time from inventory
    where site_id=1 group by tank_product) as t2
    on t1.tank_product = t2.tank and t1.timestramp = t2.time and t1.site_id=1

可以建议我通过max函数按组使用内连接的正确方法。

2 个答案:

答案 0 :(得分:0)

因此,您提供的架构和您提供的查询不会排队(命名就到处都是)。如果你提供一个sql小提示来帮助呈现你的问题(至少在未来),这将是非常有帮助的。

无论如何,我认为你很接近:

select t2.site_id, t2.tank_product, t1.volume, t2.time
from (
select site_id, tank_product, max(timestramp) as time
from inventory 
group by site_id,tank_product) t2
inner join inventory t1
on t2.site_id=t1.site_id and t1.tank_product=t2.tank_product and t2.time=t1.timestramp
inner join wp_users u
on u.id=t2.site_id
where u.id=1
order by t2.site_id,t2.tank_product asc

(假设您将wp_users.id传递给查询;我已经用u.id = 1对其进行了硬编码。)

fiddle

答案 1 :(得分:0)

尝试运行:

...
</ div>
<div class="ex">
...
相关问题