[英]What is the effective query to retrieve related information from related MySQL tables, when there can be search in both tables
I have two MySQL tables like below, and I use php to run my queries; 我有两个如下的MySQL表,并且我使用php来运行查询;
table_a table_a
+--------+--------+--------+--------+
| taf1 | taf2 | taf3 | taf4 |
+========+========+========+========+
| dataa1 | dataa2 | dataa3 | dataa4 |
+--------+--------+--------+--------+
| datab1 | datab2 | datab3 | datab4 |
+--------+--------+--------+--------+
| datac1 | datac2 | datac3 | datac4 |
+--------+--------+--------+--------+
| datad1 | datad2 | datad3 | datad4 |
+--------+--------+--------+--------+
table_b table_b
+--------+--------+--------+--------+
| tbf1 | tbf2 | tbf3 | tbf4 |
+========+========+========+========+
| dataa5 | dataa6 | dataa7 | dataa4 |
+--------+--------+--------+--------+
| datab5 | datab6 | datab7 | datab4 |
+--------+--------+--------+--------+
| datac5 | datac6 | datac7 | datac4 |
+--------+--------+--------+--------+
| datad5 | datad6 | datad7 | datad4 |
+--------+--------+--------+--------+
taf1
, taf2
, taf3
, and taf4
are fields of first table, and tbf1
, tbf2
, tbf3
, and tbf4
are fields of second table. taf1
, taf2
, taf3
和taf4
是第一个表的字段,而tbf1
, tbf2
, tbf3
和tbf4
是第二个表的字段。 taf4
and tbf4
have same entries, to link between the two tables. taf4
和tbf4
具有相同的条目,用于链接两个表。 In the results page, I display taf1
, taf2
, taf3
and tbf1
fields. 在结果页面中,我显示taf1
, taf2
, taf3
和tbf1
字段。 Also, search can be made in these 4 fields (a dropdown is given so that user can select search field). 另外,可以在这4个字段中进行搜索(给出了一个下拉列表,以便用户可以选择搜索字段)。 How can I do this? 我怎样才能做到这一点?
Currently, I use the following code; 当前,我使用以下代码;
$key = "keyword";
$field = "fieldname";
if($field == "tbf1"){
$engine = "table_b";
//search in table_b. code incomplete.
}else{
$query = "SELECT * FROM table_a WHERE $field LIKE '%$key%'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$link = $row['taf4'];
$query2 = "SELECT NUMBER FROM table_b WHERE tbf4 = '$link'";
$result2 = mysql_query($query2);
$row2 = mysql_fetch_array($result2);
echo $row['taf1']." - ".$row['taf2']." - ".$row['taf3']." - ".$row2['tbf1']."<br />";
}
}
Is there any simple and effective method to do this? 有没有简单有效的方法可以做到这一点?
SELECT taf.*,
tbf.*
FROM table_a taf
INNER JOIN table_b tbf
ON tbf.tbf4 = taf.taf4
WHERE taf......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.