سؤال

I have an orders table with a number of items related to each order:

id   | ... |  items
-----+-----+-----------------
34   | ... |  823, 27, 1657
678  | ... |  957
2548 | ... |  92, 823

Field orders.items stores contents as comma-separated id's text field. (I know the design is wrong and there should be a one-to-many table to link orders with items, but I didn't design it).

I need to select orders based on the items they contain:

SELECT id, items FROM orders
WHERE items LIKE IN (
    SELECT CONCAT('%',id,'%') FROM items
    WHERE wishlist = 0

but obviously it does not work because I can't use LIKE in a list of items obtained from IN. However, that is what I would require because I would need to use % wildcards to find them.

How can I achieve that?

EDIT:

In this SQL Fiddle there is an example of my code returning 7 lines and missing 2 of them, in which the FIND_IN_LIST function has the exact same effect on the results.

هل كانت مفيدة؟

المحلول

Try this:

SELECT DISTINCT o.id, o.items 
FROM orders AS o
INNER JOIN items AS i ON FIND_IN_SET(i.id, REPLACE(o.items, ' ', ''))
WHERE i.wishlist = 0 AND i.cost = 44800;

Check this SQL FIDDLE DEMO

OUTPUT

|  ID |      ITEMS |
|-----|------------|
| 154 |   375, 374 |
| 155 |        377 |
| 159 |        384 |
| 172 |        435 |
| 174 |        440 |
| 228 |   770, 769 |
| 229 |    775,841 |
| 230 |        777 |
| 528 | 1518, 1517 |

نصائح أخرى

SELECT id, items FROM `order` WHERE id REGEXP REPLACE(items,',','|');

SQL Fiddle

Which makes it like this,basically an advanced version of LIKE,'|' is for or

select id, items FROM test WHERE id REGEXP '823|167|398';
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top