您好,欢迎访问一九零五行业门户网

mysql一对多关联查询的时候筛选条件_MySQL

bitscn.com
mysql实现users 表和 logoin_log表是一对多, 现在是把user的信息找出来 关联上一些 logoin_log表的数据, 因为a表是多的一方,要多他的数据进行一些条件匹配,这个sql目的是查出每个用户的最新的log记录
有的人建议进行表连接来进行筛选,不过那样很麻烦,小涛我断然拒绝了,然后我采用了另一个巧妙的方法:
列表的时候采用先查一个表,这里查的是users表,然后再传值到方法,该方法进行封装查询logoin_log,此时要通过id倒序排列,返回相应的值,这样就可以获得最新的log记录了,这样是不是更简单呢,得意……坚决用表连接的盆友们,赶快试试这种方法吧。
users 表和 auth_token_log表是一对多, 现在是把user的信息找出来 关联上一些 www.111cn.net auth_token_log表的数据, 因为a表是多的一方,
要多他的数据进行一些条件匹配
这个sql目的是查出每个用户的最新的log记录
原始写法
 代码如下 复制代码
select
 users.first_name,
 users.email_address,
 users.tp_user_id,
 users.tp_username,
 auth_token_log.module_access,
 auth_token_log.created_date
from
 users
 inner join auth_token_log on users.id = auth_token_log.user_id
where
 auth_token_log.id in(
  select
  max(id)
from
  auth_token_log
where
  auth_token_log.user_id = users.id
 )
自己的理解
 代码如下 复制代码
select
 users.first_name,
 users.email_address,
 users.tp_user_id,
 users.tp_username,
 auth_token_log.module_access,
 auth_token_log.created_date
from
 users
 inner join auth_token_log on users.id = auth_token_log.user_id
where
 auth_token_log.id in(
  select
  max(auth_token_log.id)
from
  auth_token_log,
  users
where
  auth_token_log.user_id = users.id
group by
  users.id
 )
对于原始写法的理解是
先查出
 代码如下 复制代码
select
 ×
from
 users
 inner join auth_token_log on users.id = auth_token_log.user_id
的记录,  然后针对每一行记录x,拿出这一行x与 一个新的auth_token_log表做join,然后筛选出 log.user_id = x..user.id的所有记录, 然后查出max(id), 这就是最新的log记录的 id
更多详细内容请查看:http://www.111cn.net/database/mysql/56892.htm
bitscn.com
其它类似信息

推荐信息