开发者

Select info from one mysql db if value exist in another db

I have this query select latitude, longitude, username, rank from users, but I only want that info if the username exist in my online_users db. That look like this:

id bigint(20)           
userna开发者_运维百科me varchar(16)
ip varchar(39)
time datetime

So if I have 3 users in my online_users db, I want the latitude, longitude, username and rank from my users table from those 3 users. How do I do this? I assume UNION something, but my sql skills are limited.


Assuming that these are two tables in the same database, and not two databases (as stated), then either of the following will work:

SELECT latitude, longitude, username, rank 
  FROM users INNER JOIN online_users ON users.username = online_users.username

SELECT latitude, longitude, username, rank 
  FROM users WHERE username IN (SELECT username FROM online_users)


You'd use an INNER JOIN, rather than a UNION, to ensure you're getting only records with a relationship in another table:

SELECT u.latitude, u.longitude, u.username, u.rank 
  FROM USERS u
  JOIN ONLINE_USERS ou ON ou.username = u.username

This is a good introduction to joins.

If the tables are in different databases on the same MySQL instance, you prefix the table references with the respective database:

SELECT u.latitude, u.longitude, u.username, u.rank 
  FROM DB1.USERS u
  JOIN DB2.ONLINE_USERS ou ON ou.username = u.username

The user running the query will need to have access to the tables.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜