我使用2个查询是否有任何方法可以使它成为单个查询

时间:2017-01-24 06:58:42

标签: mysql sql database

这是我的情况,

我从id表中获取superadmin role=2

像这样

SELECT id FROM superadmin WHERE role='2'

假设我将获得10条记录

    id
----------------   
    3

    4

    6

    8

    10

    14

    16
    .
    .

我需要将它们传递到2nd table这样的

SELECT status FROM categorydata WHERE users='id'  // above id on each iteration

这是我在PHP中的代码:

$query_super_admin = $obj->queryAll("SELECT id FROM superadmin WHERE role='2'");
  foreach($query_super_admin['results'] as $result){
            $user_id = $result['id'];
             $category_related = $obj->queryAll("SELECT status FROM categorydata WHERE users='".$user_id."'"); 

// result data

}

问题:我想通过sql实现这一目标吗?

3 个答案:

答案 0 :(得分:2)

尝试:我认为INNER JOIN在这种情况下表现更好

SELECT c.status
from superadmin s
inner join categorydata c on s.id = c.users
where s.role='2'

答案 1 :(得分:1)

以下查询将检索用户及其状态:

SELECT s.id, c.status
FROM superadmin s
LEFT JOIN categorydata c ON s.id = c.users
WHERE s.role = 2
ORDER BY s.id;

我使用LEFT JOIN而不是像Suraz那样的INNER JOIN,因为您可能对获得没有相关状态的用户感兴趣。

然后在PHP中,为了获得与初始代码相同的行为,您可以执行以下操作:

$query = <<<EOQ
SELECT s.id, c.status
FROM superadmin s
LEFT JOIN categorydata c ON s.id = c.users
WHERE s.role = 2
ORDER BY s.id;
EOQ;

$query_super_admin = $obj->queryAll($query);
$cur_id = -1;
foreach($query_super_admin['results'] as $result) {
  if ($result['id'] != $cur_id) {
    // This is a new user id
    // Do whatever you want here, like printing user id, name, etc.

    $cur_id = $result['id'];
  }

  if (!$result['status']) {
    continue; // No status associated to this user
  }

  // Do whatever you want here, like printing status
}

答案 2 :(得分:0)

您可以使用WHERE IN (...)

SELECT status
FROM categorydata
WHERE users IN (SELECT id FROM superadmin WHERE role = '2')