Php MYSQL基于多行从表中选择
我有一个名为Php MYSQL基于多行从表中选择,php,mysql,sql,Php,Mysql,Sql,我有一个名为user\u meta的表。在该表中,我有以下列:ID,userID,meta\u键,meta\u值 我有另一个名为users的表,其中唯一重要的列是ID,我想将其与user\u meta表行进行比较 users表如下所示: ID | email | etc... 1 | email@test.com | 5 | testa@a.com | 6 | .... | 7 | .... | ID |
user\u meta
的表。在该表中,我有以下列:ID
,userID
,meta\u键
,meta\u值
我有另一个名为users
的表,其中唯一重要的列是ID
,我想将其与user\u meta
表行进行比较
users
表如下所示:
ID | email | etc...
1 | email@test.com |
5 | testa@a.com |
6 | .... |
7 | .... |
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
假设我有一个表(user_meta),看起来像:
ID | email | etc...
1 | email@test.com |
5 | testa@a.com |
6 | .... |
7 | .... |
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
我想为每个用户ID
检索一行,但前提是公司ID和用户类型正确
我想检索所有具有我将在查询中发送的相同companyID的用户,比如$companyID=2,然后检索所有具有user\u type
='staff'的用户
所以user_meta.userID必须等于users.ID,user_meta.companyID必须等于2,user_meta.user_type必须等于'staff'
我想要一个符合这些条件的所有用户的列表
结果将是返回userID
1和5。它们都有companyID=2
,都有user\u type=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')
);
对于要匹配的每个属性,您需要加入一次
user\u 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'
提供这两个表的表结构,以及来自您的示例的所需结果datas@NewbeeDev我添加了用户表,唯一重要的一列是ID.users.ID=user\u meta.userIDperhaps您想要的查询结果将有助于我们更好地理解您的问题。@NewbeeDev在底部添加了一个预期结果。这将得到公司2或员工中的所有人,不要求他们两者都是。@Barmar啊,是的,您是对的。我不明白这个问题right@PremRaj是的,谢谢你的尝试,我知道这个问题有点让人困惑。实际上这是一个很常见的要求,像这样的错误答案也很常见。这似乎正是我想要的。。我将完成编码,以确保。非常感谢。