简体   繁体   中英

Why is this MySQL statement pulling data from both tables on this JOIN?

select * from user_levels
join collectors_users on user_levels.id = collectors_users.user_level
where collectors_users.username = 'testuser'

I want it to pull everything from user_levels and nothing from collectors_users . But it's pulling from both. How do I correct the statement?

代替select *指定您实际想要的内容并使用select user_levels.*甚至更好的方法是跳过*并写出所需的列(并考虑使用别名使其简洁select ul.col1, ul.col2 ... from userlevels ul join ... ): select ul.col1, ul.col2 ... from userlevels ul join ...

It is getting all the data as the '*' means 'all' columns. You can limit the columns for just one table by specifying the table:

select user_levels.* 
from user_levels
  join collectors_users on user_levels.id = collectors_users.user_level
where collectors_users.username = 'testuser'

Pro tip: Don't use SELECT * in running software. Instead, be as specific as you can be about the columns you want in your result set.

 SELECT user_levels.* 

should help a bit.

I might suggest that you use in or exists , because this is more consistent with the intention of the query:

select ul.*
from user_levels ul
where ul.id in (select cu.user_level
                from collectors_users cu
                where cu.username = 'testuser'
               );

In addition, this version will not produce duplicate rows if collectors_users has multiple matching rows for a singel row in user_levels .

Also note the use of table aliases: these make the query easier to write and to read.

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