简体   繁体   English

从多个MySQL表中获取数据

[英]Fetch data from multiple MySQL tables

My two tables look like this: 我的两个表如下所示:

       TABLE1                      TABLE2
+--------------------+      +--------------------+
|field1|field2|field3|  and |field2|field4|field5|
+--------------------+      +--------------------+

I am already running a SELECT query for TABLE1, and assorting all of the data into variables: 我已经在为TABLE1运行SELECT查询,并将所有数据分类为变量:

$query = "SELECT * FROM TABLE1 WHERE field2 = 2";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);    
  if((!is_bool($result) || $result) && $num_rows) {
   while($row = mysql_fetch_array($result))
    {
   $field1 = $row['field1'];
   $field2 = $row['field2'];
   $field3 = $row['field3'];
    }
  }

What I want to do is get the data from 'field4' on TABLE2 and add it to my variables. 我想做的是从TABLE2上的“ field4”获取数据并将其添加到我的变量中。 I would want to get field4 WHERE field2 = 2 我想获得field4 WHERE field2 = 2

SELECT
  t1.*,
  t2.field4
FROM
  TABLE1 AS t1,
  TABLE2 AS t2
WHERE 
    t1.field2 = 2
  AND
    t1.field2 = t2.field2

You want to join the two table which can be done explicitly (using the JOIN operator or one of its variants) our implicitly (by SELECT ing from multiple tables directly). 您想将两个表JOIN ,这可以显式地(使用JOIN运算符或其变体之一)隐式地JOIN (通过SELECT直接从多个表中进行)。

From your description, I suppose that you want to do the join where field2 in the two tables have the same value ( 2 ). 根据您的描述,我假设您要进行field2 ,其中两个表中的field2具有相同的值( 2 )。


If TABLE2 will not always provide a valid join candidate but you still want the data from TABLE1 , you should use a LEFT JOIN (giving NULL for field4 where nothing matched): 如果 TABLE2并不总是提供有效的连接候选者,但是您仍然希望TABLE1的数据,则应该使用LEFT JOIN (在没有匹配field4下,为field4提供NULL ):

SELECT
  t1.*,
  t2.field4
FROM
    TABLE1 AS t1
  LEFT JOIN
    TABLE2 AS t2
  ON
    t1.field2 = t2.field2
WHERE 
  t1.field2 = 2

您需要使用JOIN

SELECT TABLE1.*,TABLE2.field4 FROM TABLE1 JOIN TABLE2 ON TABLE1.field2=TABLE2.field2 WHERE TABLE1.field2=2;

hi try the following as ur query. 嗨,尝试以下作为您的查询。

It is not preferred all the time to use * in the select query 在选择查询中始终不建议使用*

SELECT T1.field1,T1.field2,T1.field3, T2.field4 FROM TABLE1 AS T1 INNER JOIN TABLE2 AS T2 ON T1.field2=T2.field2 WHERE field2 = 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM