0

So first of all, I manged to do something like this:

SELECT * FROM `trades`
WHERE 15003 NOT IN (`slot1`, `slot2`, `slot3`, `slot4`)

And this works correct, gives me rowes without product '15003' in any of those columns. But what if I don't want to have any of '15003' or '15004' or '15008' those in query? I want to do it like this:

SELECT * FROM `trades`
WHERE 15003 NOT IN (`slot1`, `slot2`, `slot3`, `slot4`) AND
15004 NOT IN (`slot1`, `slot2`, `slot3`, `slot4`) AND
15008 NOT IN (`slot1`, `slot2`, `slot3`, `slot4`)

It works, but I think its not proper...

How can I optimize this?

Edit: Each trade has its id and 4 slots.

borewik
  • 83
  • 1
  • 7

2 Answers2

1

This is a very poor design choice, exemplified by how much difficulty you're having with this query. Instead of:

TABLE trades
  slot1 INT
  slot2 INT
  slot3 INT
  slot4 INT

should be properly normalized to something like:

TABLE trades
  trade_id INT

TABLE trades_slots
  trade_id INT
  slot_id INT

Which will allow you much more flexibility and make the queries MUCH easier to write.

SELECT *
FROM trades t INNER JOIN trades_slots s
  on t.trade_id = s.trade_id
WHERE s.slot_id NOT IN (15003, 15004, ...)
Sammitch
  • 30,782
  • 7
  • 50
  • 77
  • Hymm.. But it is INT already, not varchars. Do you mean I shouldn't use '' ? It is normalized like this, but I gave it in different form in example. – borewik Oct 24 '12 at 19:50
  • I must have been seeing things, I thought there were quotes around your numbers. And if it is normalized like this already then why is your query so broken? – Sammitch Oct 24 '12 at 20:17
0

Use a query like this:

Select *, GROUP_CONCAT(product1,product2,product3,product4) as prods
from Trades
group by ID
having prods not regexp '15003|15004|15008'
kasi
  • 774
  • 4
  • 9