views:

33

answers:

3

I have 3 tables:

  • orderProducts (orderId, productId, productValue),
  • products (productId, productName)
  • values (productId, productValue, productValuePrice).

I need to select order products (product id, name, value, price) with defined orderId. How to do that with one MySQL query?

+1  A: 

You can do this via a join, something like:

Select o.orderId, p.productId, p.name, o.productValue, v.productValuePrice
From products p
     Join values v on p.productId = v.productId
     Join orderProducts o on p.productId = o.orderId
Where orderId = 5
Nick Craver
he said "with defined orderId.", needs WHERE clause, doesn't it :)
Sarfraz
@Sarfraz - `Order`'s a keyword in my head as well evidently... Good catch, thanks!
Nick Craver
A: 

.......

 select p.productId, p.productName, o.productValue, v.prodctValuePrice from orderProducts o  join products p on o.productId = p.productId join values v on v.productId = p.productId where p.productId = 1
Sarfraz
+1  A: 

You could use a left join to return rows in the orderProducts table for which no corresponding rows in the other tables exist. Any missing columns will be NULL, allowing you to flag an error condition. The default join is an inner join, and will only return rows with matching entries in both joined tables.

select op.product id, p.name, v.productValue, p.productValuePrice
from orderProducts op
left join products p on p.productId = op.productId
left join values v 
    on v.productId = op.productId
    and v.productValue = op.productValue
where op.orderId = <YourOrderId>
Andomar
You forgot to put another condition in `left join values`, must be `left join values v on (v.productId = op.productId) and (v.productValue = op.productValue)`
Semyon Perepelitsa
@Semyon: Right, that's hard to see without knowing your data model. Answer edited
Andomar