MYSQL Select from tables based on multiple rows

后端 未结 3 686
余生分开走
余生分开走 2020-12-02 01:10

I have a table called user_meta. In that table I have the following columns: ID, userID, meta_key, meta_value

相关标签:
3条回答
  • 2020-12-02 02:01

    Not very sure about your question. I'm assuming this is what you may want:

    select * from Users where ID in (
    select userID from user_meta where (meta_key = 'companyID' and meta_value = 2) or (meta_key = 'user_type' and meta_value = 'staff')
    );
    
    0 讨论(0)
  • 2020-12-02 02:07

    You need to join with user_meta once for each attribute you want to match.

    SELECT u.*
    FROM users AS u
    JOIN user_meta AS m1 ON u.id = m1.userID
    JOIN user_meta AS m2 ON u.id = m2.userID
    WHERE m1.meta_key = 'companyID' AND m1.meta_value = :companyID
    AND m2.meta_key = 'user_type' AND m2.meta_value = 'staff'
    
    0 讨论(0)
  • 2020-12-02 02:12
    SELECT `users`.`id`, 
           `Company`.`meta_value`, 
           `UserType`.`meta_value` 
    FROM   `users` 
           JOIN `user_meta` `Company` 
             ON `Company`.`userid` = `users`.`id` 
           JOIN `user_meta` `UserType` 
             ON `UserType`.`userid` = `users`.`id` 
    WHERE  `UserType`.`meta_value` = 'staff' 
           AND `Company`.`meta_value` = 2 
    

    https://gyazo.com/de8d9124418f65b993d708c80c309325

    0 讨论(0)
提交回复
热议问题