简体   繁体   English

MYSQL查询-从2个表中获取和检查数据

[英]MYSQL Query - Get and check data from 2 tables

I have a Table name USERS where I store all my users. 我有一个表名称USERS,用于存储所有用户。 I get the user I want by using this query: 通过使用以下查询,我得到了想要的用户:

SELECT * FROM USERS WHERE username = 'Jack'

That's working nicely. 很好。

I also have another table called "Activity" when I store users following's. 当我存储用户关注的表时,我还有另一个称为“活动”的表。

I now would like to be do a query where I select the user's using the first query and then check if I am already following this user from the "Activity" table. 现在,我想做一个查询,在其中使用第一个查询选择用户的名称,然后检查是否已经从“活动”表中关注该用户。

My "Activity" table is setup like this: 我的“活动”表的设置如下:

id (for the current user / me) id(对于当前用户/我)

IdOtherUser (the id of the user that I am following) IdOtherUser(我关注的用户的ID)

type (type which is 'follow') 类型(“跟随”类型)

I know this is possible but as I am quite new to MYSQL I haven't seemed to figure it out yet, I have also checked for other similar question but have not found any helpfull! 我知道这是可能的,但是由于我对MYSQL还是很陌生,所以我似乎还没有弄清楚,我也检查了其他类似的问题,但没有发现任何帮助!

If you know any good answers already please let me know! 如果您已经知道任何好的答案,请告诉我!

Any help is much appreciated, and thanks in advance to anyone that can help!! 非常感谢您的帮助,在此先感谢任何可以提供帮助的人!

Possible solution? 可能的解决方案?

SELECT
  *,
  a.type
FROM USERS u
LEFT JOIN Activity a
   ON a.idOtherUser = u.id AND a.id = 145
WHERE u.id = 86

Check join : SQL - Joins 检查joinSQL -加入

SELECT
  u.id,
  u.username,
  a.type
FROM USERS u
LEFT OUTER JOIN Activity a
   ON u.id = a.id
WHERE a.IdOtherUser = 139

Check this one, it should work fine :) If you wonder what are these a, u, they are just aliases defined near column name. 选中它,它应该可以正常工作:)如果您想知道这些a,u是什么,它们只是在列名附近定义的别名。

IF Syntax: IF语法:

IF(expression ,expr_true, expr_false); IF(表达式,expr_true,expr_false);

You could use a LEFT OUTER JOIN and GROUP BY to count the number of matches (which might be 0), and us IF to check if there are activities or not:- 您可以使用LEFT OUTER JOIN和GROUP BY来计算匹配数(可能为0),而我们可以使用IF来检查是否有活动:-

SELECT u.id, 
    u.name,
    IF(COUNT(a.user_id) > 0, 'Activities', 'No Activities')
FROM users u
LEFT OUTER JOIN activity a
ON u.id = a.user_id
GROUP BY u.id, u.name

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

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