两个表的SQL结果和另一个表的内连接?

时间:2015-08-10 12:05:26

标签: mysql sql

所以我有两个表,customer_specialcustomer_nuk都包含完全相同的列。

我有另一张表customer_data,其编号为id

我希望运行一个查询,其结果包含来自customer_specialcustomer_nuk的所有条目,使用customer_special.user_id列和customer_nuk.user_id列中的值{{1}来自inner join的结果。

对于此示例,分别从customer_dataid的每一行返回customer_data只需返回customer_special。我尝试过各种各样的东西,但这些都不是我所希望的。

以下按预期工作;内部将customer_nuk连接到customer_data的正确行但是它没有按要求引用这两个表。

customer_special

然后:

SELECT
 t.order_id as "Order ID", t.BY1 as "By", t.order_type as "Type", t.O_DATE as "Order Date", 
 tr.short_name as "Customer short name", tr.www as "Customer website",
 tr.owner as "Customer owner", tr.postcode as "Customer postcode"
FROM customer_special t
INNER JOIN customer_data AS tr 
ON t.customer = tr.id
LIMIT 50

是我最近的尝试。

任何有关应该是一项简单任务的帮助都将受到赞赏。感谢信。

1 个答案:

答案 0 :(得分:1)

如果您希望来自两个相同表的所有数据与第三个表连接,那么您正在寻找的是union,它将从两个相同的表中生成一组数据并将该集合与第三表:

select * from (
  select * from customer_special
  union all
  select * from customer_nuk
) src
join customer_data on src.user_id = customer_data.id

请注意,使用union all不会消除任何重复的行。

*应该替换为每个表所需的列,并且对于联合中的两个表都必须相同。