简体   繁体   中英

How to: SQL Query - INNER JOIN with LIMIT 1 on the secondary table?

I have an SQL database with two tables.

One stores information about different 'casinos' in my game, and the other is the 'users' table.

Each casino record has an ownerID , corresponding to a single users ID .

I'm grabbing each row from the casinos table, and using an inner join to also grab the info about the owners user information as follows;

SELECT *
FROM casinos 
INNER JOIN users 
ON casinos.ownerID = users.ID

This works fine, but as each casino has only 1 owner, I'm wondering if it is possible to LIMIT the join on users to only attempt to select 1 row in the users table (for optimization).

Thanks.

Note: ID of users is an int column and is the tables primary key.

On DB2, we can do LATERAL joins to a query, and in that query, limit the join to a single row:

SELECT *
FROM casinos 
CROSS JOIN LATERAL (
  select   users.*
  from     users 
  where    users.ID = casinos.ownerID
  order by [some_column_that_prioritizes_best_row_to_choose]
  fetch    first row only 
) as users_one_row_only_per_casinos_row

I use that technique a LOT and it is VERY useful when I have multiple rows to choose from and only want ONE row returned from the JOIN.

If/when you need to do that kind of stuff, do a Google search on MySql and Lateral Join and I anticipate you'll find posts on how to do the equivalent in MySql.

That doesn't make sense. It's the primary key, you're joining on. You will always get just one row per casino from the users table. And there's nothing to optimize about that. If you have performance issues, consider creating an index on casinos.ownerId if you haven't done so already.

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