[英]MYSQL Select from tables based on multiple rows
我有一個名為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'
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
不太確定你的問題。 我假設這是你可能想要的:
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')
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.