简体   繁体   English

如何从两个未连接的表中选择MySQL

[英]how to select from two not joined tables in mysql

I have two tables that have no common column. 我有两个没有公共列的表。 But there is relation. 但是有关系。 I have table1, table2. 我有table1,table2。 table 1 is as follows: 表1如下:

t1.ID | t1.Name | t1.Number

Where Name is unique value. 其中Name是唯一值。

table2 is as follows: table2如下:

t2.ID | t2.Number1 | t2.Number2 | t2.Country

My query is as follows: 我的查询如下:

select t1.Name, t1.Number, t2.country
from db.t1, db.t2
where t1.Number between t2.Number1 AND t2.Number2

What is happening as a result from the query is that I get each record twice. 查询的结果是,我两次获得每条记录。 But, when I add: 但是,当我添加:

group by t1.Name

I get the correct result (each record once). 我得到正确的结果(每个记录一次)。 I do not want to use group by. 我不想使用分组依据。 How to make correct query and do I get the same record twice without group by ? 如何进行正确的查询,我是否两次获得相同的记录却没有分组依据?

Try using DISTINCT : 尝试使用DISTINCT

SELECT DISTINCT 1.Name, t1.Number, t2.country
FROM db.t1, db.t2
WHERE t1.Number BETWEEN t2.Number1 AND t2.Number2

There should be at least one column that is common to both of the tables. 这两个表应该至少有一个共同的列。 Else you 'll get duplicate values only. 否则,您只会得到重复的值。

At least to my knowledge that is the case. 至少据我所知是这种情况。

select t1.Name ,t1.Number from t1
union
select t2.Number1 ,t2.Number2 from t2

You can use union in this case. 在这种情况下,您可以使用并集。

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

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