在过去的一个月里,我一直在提高自己的MYSQL技能,但是到了无法确定该怎么做的地步。
select id, fname,lname,status, email, country_name, login_count,
(select count(ID) from applications inner join players on users.id = players.user_id inner join applications on players.id = applications.user_id where players.id = applications.player_id), (select count(ID) from messages where users.id = messages.user_id) AS '# of Messages', (select count(id) from participants where users.id = participants.user_id) AS '# of Threads', (SELECT created_at FROM messages where users.id = messages.user_id ORDER BY id DESC LIMIT 1 ) AS 'Last Message Date', updated_at
from users
where type = 'player'
#And (country_name = 'australia' or country_name = 'new zealand' or country_name = 'South Africa')
and status = 'active'
and (select count(ID) from messages where users.id = messages.user_id) = 0
and (select count(id) from participants where users.id = participants.user_id) != 0
and updated_at > '2018-10-01'
order by updated_at desc
我正在尝试获取播放器类型用户创建的应用程序数量。我还渴望获得它们所涉及的消息和线程的数量。
如果删除
,我可以很好地运行查询(从用户上的应用程序内部加入玩家中选择count(ID)。id= players.user_id玩家上的内部加入玩家中的应用程序。id= applications.user_id,其中players.id = Applications.player_id),
但是一旦我尝试获取应用程序的数量,它就会返回此
不是唯一的表/别名:“应用程序”
任何帮助将不胜感激。
(请客气,我是在自学SQL)
答案 0 :(得分:0)
您的问题是当您在此处运行子查询时:
select count(ID)
from applications
inner join players on users.id = players.user_id
inner join applications on players.id = applications.user_id
where players.id = applications.player_id
每次在给定查询中多次引用一个表时,都需要为该表引用提供唯一的别名。此查询两次触摸applications
表,因此MySQL在给定的情况下不知道您要指的是哪个表(通常,无论如何,您都应该为表起别名,因为它使EXPLAIN
语句易于调试,并使查询更具可读性。
您可以使用as
语法添加别名:
select
count(mainApps.ID)
from
applications as mainApps
inner join
players as appPlayers
on appPlayers.id = mainApps.playerId
inner join
applications as joinedApps
on appPlayers.id = joinedApps.user_id
where
users.id = appPlayers.user_id