简体   繁体   English

MySQL查询的复杂选择

[英]MySql query for complicated select

I have these tables: 我有这些表:

Users , A table contains the users: 用户 ,一个表包含以下用户:

+--------------------------
| ID    |     Name        |
+--------------------------

Dogs , A table contains the dogs (Last change is a time stamp telling when this dog status last changed): Dogs ,一个包含的表(上次更改是一个时间戳,告诉您此狗的状态上次更改的时间):

+---------------------------------------------------------
| ID    |       Name       |        Last_Changed_At      |
+---------------------------------------------------------

Users_Dogs_Relations , A table that describe which dog belong to which user, where multiple dogs can be belong to one user, multiple users can have the same dog, and multiple dogs can be belong to multiple users. Users_Dogs_Relations ,一个表,描述哪个狗属于哪个用户,其中多个狗可以属于一个用户,多个用户可以具有相同的狗,并且多个狗可以属于多个用户。 (In short, any user can be related to any dog): (简而言之,任何用户都可以与任何狗相关):

+------------------------------------
|   UserID        |     DogID       |
+------------------------------------

Users_Friend_Relation , A table describe which user is friend of which user: Users_Friend_Relation ,一个表描述哪个用户是哪个用户的朋友:

+------------------------------------
|   UserID1     |       UserID2     |
+------------------------------------

What i want to do is to tell Steve (one of the users), all the name of the dogs that his friends have (ordered by Last_Changed_At from a given timestamp). 我想做的就是告诉史蒂夫(用户之一),他的朋友们拥有的所有狗的名字(从给定的时间戳按Last_Changed_At排序)。

for example, Steve with given time 11:23:00, will query all the dogs of Steve's friends ordered by the timestamp and only below 11:23:00. 例如,给定时间为11:23:00的史蒂夫(Steve),将查询按时间戳排序且仅在11:23:00以下的所有史蒂夫(Steve)朋友的狗。 Oh, And i dont want that dogs will appear twice. 哦,我不希望狗会出现两次。 Any one can give me some clue? 任何人都可以给我一些线索吗?

You have to join all your tables on correct columns 您必须将所有表连接到正确的列

  • Users to Users_Friend_Relation to get friends of Steve UsersUsers_Friend_Relation获取史蒂夫的朋友
  • Users_Dogs_Relations to Users_Friend_Relation to get dogs of *Steve*s friends Users_Dogs_RelationsUsers_Friend_Relation获得的*史蒂夫*的朋友狗
  • Dogs to Users_Dogs_Relations to get these dogs names DogsUsers_Dogs_Relations以获取这些狗的名字

and specify your where conditions. 并指定where的条件。

SELECT DISTINCT d.Name
FROM Users u1
JOIN Users_Friend_Relation f ON u1.ID = f.User1ID
JOIN Users_Dogs_Relations udr ON udr.UserID = f.User2ID
JOIN Dogs d ON udr.DogID = d.ID
WHERE u1.Name = Steve
AND d.Last_Changed_At < '11:23:00'

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

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