mysql根据表中数据输出结果,MySQL根据另一个表中的数据从一个表返回结果

Before delving into the issue, first I will explain the situation. I have two tables such as the following:

USERS TABLE

user_id

username

firstName

lastName

GROUPS TABLE

user_id

group_id

I want to retrieve all users who's first name is LIKE '%foo%' and who is a part of a group with group_id = 'givengid'

So, the query would like something like this:

SELECT user_id FROM users WHERE firstName LIKE '%foo'"

I can make a user defined sql function such as ismember(user_id, group_id) that will return 1 if the user is a part of the group and 0 if they are not and this to the WHERE clause in the aforementioned select statement. However, this means that for every user who's first name matches the criteria, another query has to be run through thousands of other records to find a potential match for a group entry.

The users and groups table will each have several hundred thousand records. Is it more conventional to use the user defined function approach or run a query using the UNION statement? If the UNION approach is best, what would the query with the union statement look like?

Of course, I will run benchmarks but I just want to get some perspective on the possible range of solutions for this situation and what is generally most effective/efficient.

解决方案

You should use a JOIN to get users matching your two criteria.

SELECT

user_id

FROM

users

INNER JOIN

groups

ON groups.user_id = users.users_id

AND groups.group_id = given_id

WHERE

firstName LIKE '%foo'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值