简体   繁体   English

根据另一个表的值从一个表中选择

[英]Select from one table based on another tables values

I have a question if it's possible to select from one table based on another tables values in the same query. 我有一个问题,是否有可能在同一查询中从一个表中基于另一个表的值进行选择。 In my case I have two tables named follow and score . 在我的情况下,我有两个名为followscore表。

Follow 跟随

------------------------
| follower | following |
------------------------
| Uname2   | Uname1    |
------------------------

Score 得分

--------------------
| username | score |
--------------------
| Uname1   |   1   |
--------------------
| Uname1   |   2   |
--------------------

What i'm tryin to accomplice is to first get who the user is following and then get that users total score. 我要帮忙的是首先获取用户关注的对象,然后获取该用户的总得分。 I have tried with inner join etc but can't get it to work. 我尝试使用内部连接等,但无法正常工作。

Query 询问

"SELECT follow.following, score.SUM('score') FROM follow INNER JOIN score ON follow.following=score.username WHERE follow.follower='Uname2'";

To get one record use this: 要获得一条记录,请使用以下命令:

SELECT
  f.following,
  SUM(s.score) as score
FROM
  Follow f, Score s
WHERE
  f.following = s.username
  AND f.follower = 'Uname2'

To get the sum for each try: 要获得每次尝试的总和:

SELECT
  f.follower,
  f.following,
  SUM(s.score) as score
FROM
  Follow f, Score s
WHERE
  f.following = s.username
GROUP BY f.follower

Here's a Fiddle example. 这是一个小提琴的例子。

您可能需要在此处包括GROUP BY子句,在查询末尾添加GROUP BY follow.following

Use GROUP BY like this. 像这样使用GROUP BY Hope it will help. 希望它会有所帮助。

SELECT follow.following, score.SUM('score') FROM follow INNER JOIN score ON follow.following=score.username WHERE follow.follower='Uname2' GROUP BY follow.following

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM