多列主键的最小值

min value of multi column primary key

我有三个这样的table

sales_bill 包含列 (idtimeuser_idbranch_id)

sales 包含列 (idbill_idquantityitem_id)

sales_plus 包含列 (sales_idstatustimebranch_iduser_id)

其中 sales_plus.status 是 enum('add', 'remove') 并且可以在原始账单完成后添加或删除一项并且此 table 主键是sales_id 和状态

我需要 select 具有特定 bill_id 的销售额,但如果该项目被添加并从账单中删除,它只显示删除时间,branch_id 和 user_id

这是我能做的最好的,但由于 ANY_VALUE 的使用,它可以 return 添加时间但状态已删除

SELECT
bill.id as bill_id,
bill.user_id as bill_user_id,
bill.branch_id as bill_branch_id,
bill.time as bill_time,
sales.id as sales_id,
item_id,
quantity,
price,
min(status) AS status,
ANY_VALUE(sales_plus.user_id) AS sales_plus_user_id,
ANY_VALUE(sales_.branch_id) AS sales_plus_branch_id,
ANY_VALUE(sales_.time) AS sales_plus_time,
FROM sales
INNER JOIN sales_bill
ON sales.bill_id = bill.id
LEFT JOIN sales_plus
ON sales.id = sales_plus.sales_id
WHERE bill_id = :bill_id
GROUP BY sales.id

我不是 100% 确定您的目标是什么,但看起来您正在搜索销售,只有 "minimum" 状态。如果是这样,这个查询应该可以完成工作:

select * 
  from 
   sales_bill, sales, sales_plus 
  where 
    bill_id = 0 and 
    sales_bill.id = sales.bill_id and 
    sales.id = sales_plus.sales_id and 
    sales_plus.status = (
       select sp.status from sales_plus as sp where sp.sales_id = sales.id order by status limit 1
    );

这是 fiddle:http://sqlfiddle.com/#!9/37b488/2/0