代码之家  ›  专栏  ›  技术社区  ›  Steve

根据另一个表的内容在SQL中选择记录

sql
  •  9
  • Steve  · 技术社区  · 16 年前

    Table users
        int id
        varchar name
    
    Table properties
        int userID
        int property
    

    5 回复  |  直到 16 年前
        1
  •  15
  •   Gary McGill    16 年前

    使用一个 JOIN :

    SELECT U.id, U.name, P.property FROM users U
    INNER JOIN properties P ON P.userID = U.id
    WHERE property = 3
    
        2
  •  13
  •   Ken Kinder    16 年前

    如果您想选择的每个用户只有一个属性行,我认为这就是您想要的:

     select
         users.*
     from
         users,
         properties
     where
         users.id = properties.userID
         and properties.property = (whatnot);
    

    如果您有多个与“whatnot”匹配的属性行,并且您只需要一个,则根据您的数据库系统,您需要一个左连接或一个不同的子句。

        3
  •  4
  •   TLiebe    16 年前

    JOIN 命令。您可以编写如下查询:

    SELECT
        name
    FROM
        users u
        INNER JOIN properties p
            ON u.id = p.userID
    WHERE
        p.property = <some value>
    
        4
  •  3
  •   BQ.    16 年前

    你正在寻找 JOIN 桌子。

    假设id和userID列具有相同的含义,则如下所示:

    select u.name
    from users u inner join properties p
    on u.id = p.userID
    where p.property = :ValueToFind
    
        5
  •  3
  •   Wim    16 年前

    SELECT [Name] FROM Users u 
    JOIN Properties p on p.UserID=u.ID
    WHERE p.Property=1