0

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

表格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)但是,原来的问题仍然存在......无论是否匹配,我都必须显示所有行......

先感谢您。

4

2 回答 2

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)

它只返回存在于一个表中但不存在于另一个表中的行。

于 2013-05-12T19:53:22.573 回答
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

当有重名时,这将任意选择其中一个。

于 2013-05-12T20:01:49.217 回答