I know that this question has been asked several times and I’ve read all the answer but none of them seem to completely solve my problem.
I’m switching from a mySQL database to a MS Access database. In both of the case I use a php script to connect to the database and perform SQL queries.
I need to find a suitable replacement for a query I used to perform on mySQL.
I want to:
- perform a first query and order records alphabetically based on one of the columns
- construct a list of IDs which reflects the previous alphabetical order
- perform a second query with the IN clause applied with the IDs’ list and ordered by this list.
In mySQL I used to perform the last query this way:
SELECT name FROM users WHERE id IN ($name_ids) ORDER BY FIND_IN_SET(id,'$name_ids')
Since FIND_IN_SET is available only in mySQL and CHARINDEX and PATINDEX are not available from my php script, how can I achieve this?
I know that I could write something like:
SELECT name
FROM users
WHERE id IN ($name_ids)
ORDER BY CASE id
WHEN ... THEN 1
WHEN ... THEN 2
WHEN ... THEN 3
WHEN ... THEN 4
END
but you have to consider that:
- IDs’ list has variable length and elements because it depends on the first query
- that list can easily contains thousands of elements
Have you got any hint on this?
Is there a way to programmatically construct the ORDER BY CASE ... WHEN ... statement?
Is there a better approach since my list of IDs can be big?
UPDATE: I perform two separated query because I need to access two different tables.
The databse it’s not very simple so I try to make an example:
Suppose I have a table which contains a list of users and a table which contains all the books that every user have in their bookshelf.
Since the dabase was designed in mySQL, for every book record I store the user_id in the books table in order to have a relationship between the user and the book.
Suppose now that I want to obtain a list of all the user that have books with a title starting with letter ‘a’ and I want to order the user based on the alphabetical oder of the books.
This is what I do:
- perform a first query to find all the books which start with letter ‘a’ and sort the alphabetically
- create a list of user_id which should reflect the alphabetical order of the book
- perform a query in the users table to find out the users names and sort them with the user_id list to have the required sorting by book
Hope this clarify what I need.
It sounds like you need a
JOIN…This should work, although it may need to be translated to Access syntax (which is apparently subtly different):
I don’t know why you’re switching to Access, although I have heard it’s been improving in recent years. I think I’d prefer almost any other RDBMS, though. And your schema could probably stand some tweaking, from the sound of things.