Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL JOIN Tables with referenced Columns
    primarykey
    data
    text
    <p>i try to get the most(30) ordered Products from the DB.</p> <p>in Table Order i have a column type its values are (1 OR -1). 1 for valid user Order, -1 for a cancellation order(in this case the order has a reference ID to the user Order) </p> <p>reference_id is an id of another Order (in the same order table)| one row referenced to another row.</p> <p>Order Table:</p> <pre><code>id | reference_id | type ---------------------------------- 1 | | 1 ---------------------------------- 2 | | 1 ---------------------------------- 3 | 1 | -1 ---------------------------------- </code></pre> <p>Products Table:</p> <pre><code>id | order_id | quantity ---------------------------------- a | 1 | 4 ---------------------------------- b | 2 | 7 ---------------------------------- a | 3 | 2 ---------------------------------- </code></pre> <p>MySQL Query: </p> <pre><code>SELECT *, sum(product.quantity) as quantity, count(*) as score FROM product LEFT JOIN order ON ( product.order_id=order.id ) WHERE (..?..) GROUP BY product.id ORDER BY score DESC LIMIT 30; </code></pre> <p>this will select, sum and count all Products in all Orders.</p> <p>BUT:</p> <p>what i am looking for is: </p> <pre><code>if(order.type &lt; 0 ){ product.quantity is in minus(-) (quantity of the Product in the referenced Order MINUS this.product.quantity) } </code></pre> <p>how to do this in the SQL Statement? i tried somany things but without success</p> <p><strong>as per comments requested Example:</strong> result should be a LIST of ordered Products grouped by product.id Most Ordered Products:</p> <pre><code>Product-id | quantity ------------------------------------------- a | 2 (in 2 Orders) ------------------------------------------- b | 7 (in 1 Order) ------------------------------------------- c | 12 (in 3 Orders) ------------------------------------------- ...etc. </code></pre> <p>many thanks</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload