1

I've a problem with MySQL query. I'm trying select products info over the order products list, but it are selecting only the first record, being that the products list is a array. Example: being orders.itens = "10,11,12,13", the "IN" selects only the first ID, "10". How I do to select all ID's, something that sounds like implode function in PHP?

SELECT
    orders.id,
    products.name,
    products.price
FROM 
    orders,
    products
WHERE
    products.id IN (orders.itens)

Thank you

4
  • 2
    You need to give the values seperately in th IN clause like IN ("10","11","12","13") Commented Mar 20, 2014 at 14:41
  • And how I do to separate the values into a MySQL query? Commented Mar 20, 2014 at 14:44
  • 1
    How are you getting the values for in clause Commented Mar 20, 2014 at 14:45
  • I'm using a multiple mysql query, so I can't use any PHP functions.. The orders.itens row is exactly how I posted: "10,11,12,13". I need a MySQL function to divide.. Commented Mar 20, 2014 at 14:48

2 Answers 2

2

You want to do a join:

SELECT o.id, p.name, p.price
FROM orders o join
     products p
     on find_in_set(p.id, o.items) > 0;

Unfortunately, there is no way to optimize this query. You should created an association/junction table, probably called OrderProducts that contains one row for each product in an order.

Sign up to request clarification or add additional context in comments.

4 Comments

But if I'll create a row for each product, the table will be giant
@CristianAugusto . . . This is how databases are designed to be used. What is "giant" anyway? Unless you are talking about billions of rows, then your table is not "giant".
But if a order have 10 products, how I do to create a row for each product?
@CristianAugusto . . . You need to re-organize your database so you have an OrderProducts table. Such as table would have rows like (Order=1, Product=a), (Order=1, Product=b), and (Order=1, Product=c). A separate row for each product in an order. Google "junction table" or "association table" -- you'll get lots of hits with lots of explanation.
1

I guess you need something like this

select CONCAT('"',CONCAT(Replace("10,11,12,13", ',', '","'),'"')) as str

And use this as the value for in clause

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.