简体   繁体   English

在两个相关表之间查询

[英]Query between two related tables

I have to tables. 我要桌子。 One of them, user_profile , has a field named user_profile_id and the other table, user_friend , has two fields named user_profile1_id and user_profile2_id (which are FK to the first table). 其中一个user_profile具有一个名为user_profile_id的字段,另一个表user_friend具有两个名为user_profile1_iduser_profile2_id字段(它们在第一个表中都是FK)。

I want to check if there is any users in user_profile which is not in user_friend table, neither in user_profile1_id, nor user_profile2_id. 我想检查user_profile中是否有任何用户,这些用户不在user_friend表中,也不在user_profile1_id和user_profile2_id中。 what query should I use !? 我应该使用什么查询!

First of all I suggest you to use a circular foreign key in the user_profile_table where the foreign key refers back to the primary key of the same table. 首先,我建议您在user_profile_table中使用循环外键,其中外键指回同一表的主键。 This way you save yourself creating another table just for relationships between users. 这样,您就不必为用户之间的关系创建另一个表。

However, using your design, you can use the following query: 但是,使用您的设计,可以使用以下查询:

SELECT user_profile_id 
FROM user_profile A
 WHERE 
  NOT EXISTS(
      SELECT * FROM user_friends B 
       WHERE B.user_profile1_id=A.user_profile_id OR 
             B.user_profile2_id=A.user_profile_id
            )

Try this 尝试这个


SELECT * FROM users
LEFT JOIN friends f1 ON (users.id = friends.uid)
LEFT JOIN friends f2 ON (users.id = friends.fid)
WHERE f1.uid IS NULL AND f2.uid IS NULL

Try (this is MSSQL but it should be similar in MySQL) 试试(这是MSSQL,但在MySQL中应该类似)

select 
   *
from
   user_profile up
   left join user_friend uf
     on up.user_profile_id = uf.user_profile1_id
     or up.user_profile_id = uf.user_profile2_id
where
     coalesce(uf.user_profile1_id,uf.user_profile2_id) is null

Try: 尝试:

SELECT user_profile_id 
FROM user_profile
WHERE 
  user_profile_id NOT IN (SELECT DISTINCT user_profile1_id FROM user_friend)
  AND user_profile_id NOT IN (SELECT DISTINCT user_profile2_id FROM user_friend)

There are probably more efficient queries, but this should do the job. 可能存在更有效的查询,但这应该可以完成工作。

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

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