使用INNER JOIN / JOIN进行多次查询

时间:2014-02-14 10:50:56

标签: php mysql join pdo inner-join

我现在所拥有的是与law_case的案例相匹配![在此处输入图片说明] [1]

$query1 = "SELECT * FROM law_case WHERE id =?";
$query1vals = array($_GET['id']);
$ids = $adb->selectRecords($query1, $query1vals, false);
$a = $ids['case_type_id'];
$b = $ids['funding_pref'];
#
$query2 = "SELECT type_name FROM case_type WHERE id =?";
$query2vals = array($a);
$ids1 = $adb->selectRecords($query2, $query2vals, false);
$d = $ids1['type_name'];
#
$query3 = "SELECT * FROM expertise WHERE expertise_desc =?";
$query3vals = array($d);
$ids2 = $adb->selectRecords($query3, $query3vals, false);
$c = $ids2['id'];
#
$query4 = "SELECT * FROM individual_expertise WHERE expertise_id =?";
$query4vals = array($c);
$ids3 = $adb->selectRecords($query4, $query4vals, false);
$e = $ids3['individual_id'];
#
$query5 = "SELECT * FROM individual WHERE id =?";
$query5vals = array($e);
$ids4 = $adb->selectRecords($query5, $query5vals, false);
$f = $ids4['network_member_id'];
#
$query6 = "SELECT * FROM network_member WHERE id =?";
$query6vals = array($f);
$ids5 = $adb->selectRecords($query6, $query6vals, false);

它做了什么它只获得一个network_member。 我想使用INNER JOIN,JOIN或LEFT JOIN并使用一段时间来获取每个network_member的不同member_name和url,或者谁的个人具有individual_expertise表中相同的expertise_id。

我是JOIN的新手并尝试过这段代码,但它不起作用:

$sql = "SELECT member_name, url
FROM individual_expertise
LEFT JOIN individual
USING (individual_id)
LEFT JOIN network_member
USING (network_member_id)
WHERE expertise_id = ?";
$ids3 = $adb->selectRecords($sql, $query4vals, false);

echo $ids3['member_name'];

2 个答案:

答案 0 :(得分:0)

您需要了解JOIN类型的概述。您必须使用INNER, LEFT, RIGHT, FULL连接构建查询,具体取决于您的逻辑要求。您可以假设INNER join等于条件语句中的&&AND运算符,我的意思是两个表中的记录必须匹配。 同时,LEFT join将返回左连接表中的所有行以及右连接表中的匹配行。 RIGHTLEFT相反。 FULL join是条件语句中运算符中||OR的示例。我的意思是两个表中都匹配。 所以你必须根据你需要的逻辑加入。

See here

答案 1 :(得分:0)

你知道INNER JOIN和LEFT JOIN之间的区别吗?我想你没有。你需要一个INNER JOIN。

我认为这是您问题的正确解决方案:

SELECT
    network_member.member_name,
    network_member.url
FROM
    network_member
INNER JOIN
    individual ON individual.network_member_id = network_member.id
INNER JOIN
    individual_expertise ON individual_expertise.individual_id = individual.id
WHERE
    individual_expertise.expertise_id = ?