我有一个名为user_meta
的表。在该表中,我有以下列:ID
、userID
、meta_key
、meta_value
我有另一个名为 users
的表,其中唯一重要的列是 ID
,我想将其与 user_meta
表行进行比较。
users
表如下所示:
ID | email | etc...
1 | email@test.com |
5 | testa@a.com |
6 | .... |
7 | .... |
假设我有一个表(user_meta),如下所示:
ID | userID | meta_key | meta_value
2 | 1 | companyID | 2
3 | 1 | user_type | staff
4 | 5 | companyID | 2
5 | 5 | user_type | staff
6 | 6 | companyID | 4
7 | 6 | user_type | customer
我想为每个 userID
检索一行,但前提是公司 ID 和 user_type 正确。
我想要检索具有与我在查询中发送的相同 companyID 的所有用户,因此假设 $companyID=2,然后是具有 user_type
='staff' 的所有用户。
因此 user_meta.userID 必须等于 users.ID,user_meta.companyID 必须等于 2,user_meta.user_type 必须等于 'staff'。
我想要一个符合这些条件的所有用户的列表。
返回的结果是userID
1 & 5。他们都有 companyID = 2
,并且都有 user_type = Staff
最佳答案
您需要为每个要匹配的属性加入 user_meta
一次。
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'
关于php - MYSQL 根据多行从表中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54260812/