MySQL使用一个条件从两个表连接

时间:2013-05-28 03:30:43

标签: php mysql join

我无法想出加入..
需要从一个表中选择所有行,其中列等于另一个表中的某些内容。

像这样:

SELECT ALL FROM someTable 
WHERE COLUMN someColumn = '123' (IN A DIFFERENT TABLE) 
像那样...... 并且ID当然需要匹配..

2 个答案:

答案 0 :(得分:4)

只需使用INNER JOIN

SELECT * 
FROM SomeTable S
    JOIN SomeOtherTable S2 
        ON S.SomeKey = S2.SomeKey
WHERE S.SomeColumn = '123'

我并不完全清楚您的问题,因此如果代表您的WHERE条件,则可能不需要JOIN条款。

答案 1 :(得分:0)

A bit error in my question, let me clarify
tblplace
id  place
1  London
2  Paris
3  New York

tbltraveller
tr_id  tr_name    id
1       John      3
2       Jackson   2
3       Susanna   1
4       Jimmy     3
5       Lucy      2

该问题缺少纽约的一些数据:

Paris         Jackson Lucy
New York

我的代码(猜测while循环中有错误):

<?php
require_once("connMysql1.php");
$qry = "SELECT * FROM tblPlace WHERE tblPlace.id > 1 ORDER BY tblPlace.id";
$result = mysqli_query($db_link, $qry);
$qry1 = "SELECT tblPlace.id, tblPlace.Place, tbltraveller.tr_id, 
tbltraveller.tr_name, tbltraveller.id FROM tblPlace INNER JOIN tbltraveller ON 
tblPlace.id = tbltraveller.id WHERE tblPlace.id > 1 ORDER BY tbltraveller.id";
$result1 = mysqli_query($db_link, $qry1);
$no_of_row1 = mysqli_num_rows($result1);
$no_of_row = mysqli_num_rows($result);
echo "<table border=1 cellpadding=10>";
if ($no_of_row >0){
while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td>";
echo $row['place']."<br>";
echo "</td>"."&nbsp;";
echo "<td>";
while ($row1 = mysqli_fetch_assoc($result1)){
if($row1['id'] == $row['id']){
echo $row1['tr_name']."&nbsp;&nbsp;&nbsp;";
}
}
echo "</td>";
"</tr>";
}
}
echo "</table>";
?>

`