0

I have two tables and i need to get list of all store_ids that are not in the other table

BusinessUnit Table   User Table
StoreId(varchar)     StoreId(varchar)
1                    1,2
2                    3,4
3                    1,5
4                    4,6
7                    4

How to get values of storeid 5,6 which are not present in the business unit table but are present in the user Table? Tried to use several using find_in_set and nothing works.

Learner2011
  • 287
  • 2
  • 6
  • 25

2 Answers2

0

IF you know all the possible values (and the number of them is reasonably manageable) you can populate a new table with them (you can make it TEMPORARY or just DROP it afterwards), and do this

SELECT * 
FROM (
      SELECT allIDs.Id 
      FROM allIDs 
         INNER JOIN `User` AS u 
         -- ON CONCAT(',', u.StoreID, ',') LIKE CONCAT('%,', allIDs.Id, ',%')
         ON FIND_IN_SET(allIDs.Id, u.StoreID)
   ) AS IDsInUserTable
   LEFT JOIN `BusinessUnit` AS b ON IDsInUserTable.Id = b.StoreID
HAVING b.StoreID IS NULL
;

In this example, allIDs is the aforementioned "possible values" table.

Uueerdo
  • 15,723
  • 1
  • 16
  • 21
  • Why not use `FIND_IN_SET` instead of all that CONCAT and LIKE stuff? – Barmar May 14 '15 at 17:07
  • @Barmar because he is trying to find values in the csv field in Users that are not in the BusinessUnit table, not values in the BusinessUnit table that are or are not in the Users table's csv field. – Uueerdo May 14 '15 at 17:12
  • I mean when you're joining between `AllIDs` and `User`. – Barmar May 14 '15 at 17:12
  • `ON FIND_IN_SET(allIDs.Id, u.StoreId)` – Barmar May 14 '15 at 17:13
  • Oh, haha, true that would probably be better; I've never actually had use for `FIND_IN_SET` so it doesn't spring to mind to use it. – Uueerdo May 14 '15 at 17:14
  • You're probably smart enough not to put CSV in your tables, so you don't need it much. – Barmar May 14 '15 at 17:15
  • I'd like to think so, but I am sure have done equivalently bad stuff in other areas. Everyone has their strengths and weaknesses. – Uueerdo May 14 '15 at 17:19
0

Use SUBSTRING_INDEX to get all the values from the CSV field. Since there can be up to 6 IDs in the CSV, you need to call it once for each position.

SELECT u.StoreId
FROM (
    select substring_index(StoreId, ',', 1) AS StoreID
    FROM User
    UNION
    select substring_index(substring_index(StoreId, ',', 2), ',', -1)
    FROM User
    UNION
    select substring_index(substring_index(StoreId, ',', 3), ',', -1)
    FROM User
    UNION
    select substring_index(substring_index(StoreId, ',', 4), ',', -1)
    FROM User
    UNION
    select substring_index(substring_index(StoreId, ',', 5), ',', -1)
    FROM User
    UNION
    select substring_index(substring_index(StoreId, ',', 6), ',', -1)
    FROM User) AS u
LEFT JOIN BusinessUnit AS b ON u.StoreId = b.StoreID
WHERE b.StoreId IS NULL

DEMO

Barmar
  • 741,623
  • 53
  • 500
  • 612