获取关联错误

时间:2015-10-28 04:14:38

标签: php sql mysqli union fetch

你好

我试图用这个查询创建一个表但我无法让它工作。问题是,它不能一次选择2个查询,但我不知道另一种方式...

    WITH LastRow (id)
    AS (
       SELECT MAX(id) 
       FROM TheTable
       GROUP BY item, group_id    
    )
    SELECT group_Id, SUM(val), SUM(CASE WHEN B.id IS NULL THEN 0 ELSE cost END)
    FROM TheTable A
      LEFT OUTER JOIN LastRow B ON A.id = B.id
    GROUP BY group_id

2 个答案:

答案 0 :(得分:0)

试试这个:

$active_ids = '1, 3, 4';
$result = $mysqli->query("
    (SELECT * FROM users WHERE id IN ({$active_ids}))
    UNION 
    (SELECT dj, count(*) AS n FROM timetable WHERE dj IN ({$active_ids}) GROUP BY dj)
") ;

if (!$rec = mysqli_fetch_array($result)) {
    echo ("Sorry, no records found");
}
else {
    do {
        echo ($rec["username"]);
        echo "<br />";
        echo ($rec["n"]);
        echo "<br />";
    }
    while ($rec = mysqli_fetch_array($result));
}

答案 1 :(得分:0)

     $active_ids = '1, 3, 4'; 

    $query = "SELECT users.* from users 
              LEFT JOIN timetable ON users.id=timetable.dj
                  WHERE users.id IN ({$active_ids})
              UNION
              SELECT timetable.dj,timetable.count(*) as n from timetable
              RIGHT JOIN users ON timetable.dj=users.id
                  WHERE timetable.dj IN ({$active_ids}) GROUP BY timetable.dj
    ";
    $result = $mysqli->query($query);    

    while($row = $result->fetch_assoc()){
        echo $row['username'], "<br/>";
        echo $row['n'], "<br/>";
    }

我不知道这肯定是真的,但你可以试试这段代码吗?