从具有相同列的两个表中输出数据并将变量添加为标识符

时间:2013-05-12 19:46:22

标签: php mysql database variables

假设我有两个表,列名相同,当我想将它们输出到表中时,我只想要一个额外的字段来向用户显示它来自哪个表... 即。

表1

---------------------------------------------------
ID| name | address | another_identifier|  color
-------------------------------------------------
1 | Bob  | 123 Nowhere | 12345         |  gray
2 | Jane | 321 nowhere | 54321         |  red
3 | Jack | 555 somewhere | 12993       |  blue

表2

------------------------------------------------
ID| name | address | another_identifier|  color
------------------------------------------------
1 | Bob  | 123 Nowhere | 12345         | purple
2 | Jane | 321 nowhere | 54321         | green
3 | Jack | 555 somewhere | 12993       | blue

查询

$query = "SELECT a.*, b.* FROM table1 a, table2 b";
$results = $class->runQuery($query); // basically a fetchAll to create an array

显示代码

foreach($results as $row){          
$html .= "<tr>";
//Now print the name            
$html .= "<td>" . $row['name'] . "</td>";
// Print the address
$html .= "<td>" . $row['address'] . "</td>";

//NOW PRINT WHAT TABLE ITS FROM
if (table == "table1")
    $html .= "<td>Its from Table 1</td>";
else if (table == "table2")
    $html .= "<td>Its From Table 2</td>";

$html .= "</tr>";
        }
print $html;

附注

1)请不要假设两个表都包含相同的信息......出于示例目的,有一个省略的列

2)为了帮助不再提出其他问题,请问您还可以回答:如何修改我的原始$query以不显示具有相同name列的行

3)然而,原始问题仍然存在......无论是否匹配,我都必须显示所有行....

提前谢谢。

2 个答案:

答案 0 :(得分:2)

如果我理解你的问题,我会使用这样的UNION查询:

SELECT 'table1' As table_name, table1.*
FROM   table1

UNION ALL

SELECT 'table2' As table_name, table2.*
FROM   table2

这将选择table1中的所有行和table2中的所有行,以及记录来自的表的名称。

两个表都需要具有相同的结构,否则您需要指定列名:

SELECT 'table1' As table_name, table1.ID, table1.name,
       table1.address, table1.another_identifier
FROM   table1

UNION ALL

SELECT 'table2' As table_name, table2.ID, table2.name,
       table2.address, table2.another_identifier
FROM   table2

要回答第二个问题,您可以使用此查询仅返回一次记录:

SELECT MIN(table_name), ID, name, address, another_identifier
FROM (
  SELECT 'table1' As table_name, table1.ID, table1.name,
         table1.address, table1.another_identifier
  FROM   table1

  UNION ALL

  SELECT 'table2' As table_name, table2.ID, table2.name,
         table2.address, table2.another_identifier
  FROM   table2) s
GROUP BY
  ID, name, address, another_identifier

(如果两个记录都存在,它将返回table1。)

或者你可能需要使用它:

SELECT 'table1' As table_name, table1.*
FROM   table1
WHERE  NOT EXISTS (SELECT name FROM table2 WHERE table2.name=table1.name)

UNION ALL

SELECT 'table2' As table_name, table2.*
FROM   table2
WHERE  NOT EXISTS (SELECT name FROM table1 WHERE table1.name=table2.name)

仅返回一个表中存在的行,但不返回另一个表中的行。

答案 1 :(得分:1)

fthiella已回答了问题3.问题2可以使用GROUP BY解决:

SELECT *
FROM (SELECT 'table1' As table_name, table1.*
      FROM   table1

      UNION ALL

      SELECT 'table2' As table_name, table2.*
      FROM   table2) x
GROUP BY name
ORDER BY name

如果名称重复,则会随意选择其中一个。