sql join重复结果

时间:2014-11-05 15:32:32

标签: php mysql sql

我需要列出打印所有按健身房名称订购的客户的清单,但它重复健身房的名称与健身房的客户数量相同。如果gym1有4个客户,则echo会打印4次。

表/列是:

members (id, gym, name, etc...)

gym (gymID, gym_name, etc...).

member.gym应了解客户所属的gymgym.gymID

if ($stmt = $mysqli->prepare("  SELECT DISTINCT g.*, m.*
                                FROM gym g
                                INNER JOIN members m ON m.gym = g.gymID")) {

    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_array()) {
        echo 'Sport center: ' . $row['gym_name'] . '<br>';
        // here print the gym's clients list
    }

}

DISTINCT无法正常工作......问题是什么?

4 个答案:

答案 0 :(得分:1)

这是正常行为。

示例

考虑以下表格

Table "gym"
-----------
gym_id | gym_name
-------+----------
  1    |  Gym A
  2    |  Gym B

Table "members"
---------------
member_id | gym_id | member_name
----------+--------+------------
  1       |  1     | Bob
  2       |  1     | Jeff

现在,执行此查询:

select g.gym_id, g.gim_name, m.member_id, m.member_name
from gym as g
     inner join members as m on g.gym_id = m.gym_id;

结果:

gym_id | gym_name | member_id | member_name
-------+----------+-----------+-------------
  1    |  Gym A   |   1       |   Bob
  1    |  Gym B   |   2       |   Jeff

这是因为gym表中的每一行都与members名称中的行匹配。即使您使用select distinct,结果也会相同,因为每一行都不同。

我认为你想要的是这样的输出:

 Gym A
      Bob
      Jeff

虽然可以直接在SQL中完成,但是使用PHP直接处理它更容易,因为在SQL 中执行它会是一个真正的痛苦需要写一个相当的复杂的查询。我对PHP不太满意,但它可能是这样的:

/*
 You don't need "DISTINCT", but you need "ORDER BY" to make this work
 */
if ($stmt = $mysqli->prepare("  SELECT g.*, m.*
                                FROM gym g
                                INNER JOIN members m ON m.gym = g.gymID
                                ORDER BY g.gymID")) {

    $stmt->execute();
    $result = $stmt->get_result();
    $gym = "";
    while ($row = $result->fetch_array()) {
        if($row['gym_name'] != $gym)
            echo 'Sport center: ' . $row['gym_name'] . '<br>';
        echo '   Member: ' . $row['member_name'] . '<br>';
        $gym = $row['gym_name'];
    }

}

答案 1 :(得分:0)

首先,将DISTINCT和一巴掌放入ORDER BY

SELECT g.*, m.*
FROM gym g
INNER JOIN members m ON m.gym = g.gymID
ORDER BY g.name;

现在,调整您的PHP代码只打印健身房名称,如果它与您上次打印的健身房不同。

答案 2 :(得分:0)

SELECT g.*, m.*
FROM gym g
INNER JOIN members m ON m.gym = g.gymID
ORDER BY g.name,gym_clients;

我不知道Gym Name列的名称和&amp;健身房客户专栏因此,如果拼写错误,请更改名称。 我希望这对你有用

答案 3 :(得分:0)

这应该有效:

SELECT *
FROM gym g
LEFT JOIN members m 
     ON g.gym_ID=m.gym_id 
GROUP BY g.gym_name