Pergunta

I have a table where 2 columns represent user-IDs. The order of the IDs can be either way (depends on who initiated the process) I need to retrieve the rows for a combination of 2 users (either way).

To test I added a key on (user1, user2) and one on (user2, user1) but it ends up using neither.

My question is, what do you guys think the quickest/lowest overhead would be?

The "traditional" way:

SELECT * FROM table WHERE (user1 = 1 AND user2 = 2) OR (user1 = 2 AND user2 = 1)  

Or with in():

SELECT * FROM table WHERE user1 IN (1, 2) AND user2 IN (1, 2)

I'm operating under the assumption here that a no records exist where user1 = user2, so unless I'm missing something both should result in the correct records.

Edit: fiddle

Foi útil?

Solução

Your schema and queries are fine, MySQL just chooses to not use indexes when you have only a few rows.

Updated fiddle with a few more rows

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top