简体   繁体   English

MySQL通过两个表中的一个查询获取关系用户

[英]MySQL get relations users by one query from two tables

Im trying to get list of "friends" from my tables. 我试图从我的表中获取“朋友”列表。 I have a two tables, one where I store users list, and second one where I store relations with this users. 我有两个表,一个表存储用户列表,第二个表存储与该用户的关系。 I add on sqlfiddle example schemas. 我添加了sqlfiddle示例架构。 I need to fetch all "friends" for specified user id: 我需要获取所有指定用户ID的“朋友”:

CREATE TABLE tbl_users
    (`id` int, `name` varchar(7), `description` varchar(55));

INSERT INTO tbl_users
    (`id`, `name`, `description`)
VALUES
    (1, 'John', '111'),
    (2, 'Derrik', '222'),
    (3, 'Nikolas', '333'),
    (4, 'Hellen', '444'),
    (5, 'Jack', '555');

CREATE TABLE tbl_relations
    (`id` int, `user_id` int, `following_id` int);

INSERT INTO tbl_relations
    (`id`, `user_id`, `following_id`)
VALUES
    (1, '1', '2'),
    (2, '1', '3'),
    (3, '1', '4'),
    (4, '2', '1'),
    (5, '4', '1');

Yes, I can do two queries and then compare it, but I thing this should work with one. 是的,我可以进行两个查询,然后进行比较,但是我认为这应该可以解决一个问题。

Result expected: if specified user id = 1, result should be get 2,4 user 预期结果:如果指定的用户ID = 1,则结果应为2,4个用户

Thx. 谢谢。

If the table 如果表

  1. users 使用者
  2. relations 关系

The two tables must have columns that have the same value. 这两个表的列必须具有相同的值。 If the columns is user_id so 如果列是user_id ,则

SELECT * from users,relations WHERE users.user_id = relations.user_id;

I hope this answer can help you :) 我希望这个答案可以帮助您:)

try this: 尝试这个:

SELECT tbl_users.* 

FROM tbl_users

INNER JOIN tbl_relations ON tbl_relations.user_id = tbl_users.id

More about join 有关加入的更多信息

"Result expected: if specified user id = 1, result should be get 2,4 user" “预期结果:如果指定的用户ID = 1,则结果应为2.4个用户”

SELECT x.following_id reciprocations
  FROM tbl_relations x 
  JOIN tbl_relations y 
    ON y.user_id = x.following_id 
   AND y.following_id = x.user_id 
 WHERE x.user_id = 1;

This should return 2,3 for user id 1 这应该为用户ID 1返回2,3

SELECT id FROM tbl_relations 
WHERE user_id = 1 AND id != user_id;

To get the friends instead of their ids use 要获取朋友而不是其ID,请使用

SELECT * from tbl_users WHERE id IN (SELECT id FROM tbl_relations 
WHERE user_id = 1 AND id != user_id);

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

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