简体   繁体   中英

MySQL select values from one table based on array of ids from another table

I found many PHP examples which use map and implode to structure their string...I'm using Node and Javascript and I think that might be the problem. I have an array of ids and I'm saving it like this:

[1, 2, 3, 4].join();

That's being stored and I'm trying to run a query:

SELECT sr.id, sr.name, sr.city FROM table1 AS sr 
JOIN table2 AS st WHERE sr.city = st.city AND sr.id IN (st.ids);

So both tables have a column city, table2 having multiple records, table1 only has one. The 'ids' column is of type TEXT in table2. Problem is it's only returning the row with id 1. If I do this:

SELECT sr.id, sr.name, sr.city FROM table1 AS sr 
JOIN table2 AS st WHERE sr.city = st.city AND sr.id IN (1,2);

I will get rows 1 and 2. What's causing the problem? I tried [1, 2, 3, 4].join(', '); and that didn't help. Any suggestions?

I'm using MySQL v5.7 so I have access to JSON functions...I should've used this in the first place. The solution which works as I wanted is:

SELECT sr.id, sr.name, sr.city FROM table1 AS sr 
JOIN table2 AS st WHERE sr.city = st.city AND 
JSON_SEARCH(st.ids, 'one', sr.id) IS NOT NULL;

Love the new JSON support feature...altho it comes with its caveats. For example, the ids in the array have to be strings, the ids cannot be int 's. JSON_SEARCH kept on returning NULL for paths to the ids until I converted them to strings. Trial and error...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM