查询两个表有问题

时间:2014-02-10 21:07:02

标签: php mysql select

我有两个表(这里有随机数据)

 cu                         cgm
+-----+---------+-----+    +---------+--------+
| uid | name    | ... |    | groupid | userid |
+-----+---------+-----+    +---------+--------+
|   1 | manfred | ... |    |       2 |      2 |
|   2 | peter   | ... |    |       2 |      5 |
|   3 | jackson | ... |    |       2 |      7 |
| ... |  ...    | ... |    |       4 |      3 |
+-----+---------+-----+    +---------+--------+
  uid <========= FOREIGN KEY ========== userid

我希望按cu.name选择cu.uidcgm.userid / cgm.groupid,然后将值放入关联数组中,其中键为cu.name,值为cu.uid cgm.userid / cgm.userid。我唯一的解决方案是发送查询以cgm.groupid选择cu.name,发送第二个查询以cu.uid选择{{1}}并将数据放在一起。但我想知道,如果只有一个查询可以实现这一点,并尽可能少地使用PHP。

3 个答案:

答案 0 :(得分:2)

带左键的SQL可能是:

SELECT cu.name, cu.uid, cgm.userid, cgm.userid, cgm.groupid
FROM cu
LEFT JOIN cgm ON cu.uid = cgm.userid
WHERE cgm.groupid = 2 -- your var there

虽然在这种情况下您不需要选择cgm.userid,因为它应该与cu.uid相同(如果不是,则此连接不正确)。

使用PHP:

$group_id = 2;
$sql = "SELECT ..... WHERE cgm.groupid = " . $group_id;
$query = $db->query($sql); // your query functions here...

To help you avoid SQL injection, your should bind $group_id作为参数:

$sth = $db->prepare("SELECT ... WHERE cgm.groupid = :group_id");
$sth->bindParam(':group_id', $group_id, PDO::PARAM_INT); // only accept integers
$sth->execute();

更多信息:

答案 1 :(得分:1)

SELECT cu.name, cu.uid FROM cu LEFT JOIN cgm ON cu.uid = cgm.userid WHERE cgm.groupid = 2

您可以根据需要调整WHERE条件。

答案 2 :(得分:0)

是的,你可以通过使用join来实现。使用以下查询。

select uid,name from cu,cgm where uid=userid and groupid =<GROUP_ID>;

您可以使用PDO连接数据库。

$conn= new PDO('mysql:host=localhost;dbname=chatting4u','root','');
    $stmt=$conn->prepare('select uid,name from cu,cgm where uid=userid and groupid =<GROUP_ID>');
    $stmt->execute();
    $row=$stmt->fetchall(PDO::FETCH_ASSOC);

现在你将获得uid,在$ row数组中取消命名。尝试一下,我希望它会起作用。

参考文献: -

Databse Joins-&gt; http://www.w3schools.com/sql/sql_join.asp

PHP中的PDO-&gt; http://www.php.net/manual/en/book.pdo.php

相关问题