在MySQL中使用一个常用键连接两个表

时间:2023-01-04 15:29:59

I have two tables:

我有两个表:

Table 1

表1

id  app_name  app_id
1    name1    12001
2    name2    12002
3    name2    12002
3    name3    12003

And second

和第二

Table 2

表2

id  app_id
1   22001
2   22002
3   12003
4   22002

How can I show data from this tables for app_id's that are same?

如何显示app_id相同的表中的数据?

In this example correct SQL should show

在这个示例中,应该显示正确的SQL

name3 12003

I already tried all types of JOIN and also select * from table1, table2 where table1.app_id=table2.app_id, but it seems that I am missing something simple.

我已经尝试了所有类型的JOIN,并从table1中选择了*,table2中table1.app_id=table2。app_id,但是我似乎漏掉了一些简单的东西。


CORRECT ANSWER

正确的答案

Unprintable symbol that appeared after clipboard copying data for database inserting led to this problem. Column values were not identical in two tables. It can be checked by making SQL dump and examinig it manually or with hex editor.

在剪贴板复制数据库插入数据后出现的不可打印符号导致了这个问题。两个表中的列值不相同。可以通过创建SQL转储并手动检查它,或者使用十六进制编辑器检查它。

3 个解决方案

#1


3  

SELECT Table1.app_name, Table1.app_id
FROM Table1
INNER JOIN Table2 ON Table1.app_id = Table2.app_id

#2


1  

The query you posted should work (although I would strongly recommend that you use the JOIN keyword rather than the comma syntax).

您发布的查询应该有效(尽管我强烈建议您使用JOIN关键字,而不是使用逗号语法)。

I suspect that your problem is that your tables have not been created correctly. Use the following commands to debug the problem - and pay particular attention to the data types:

我怀疑您的问题是您的表没有被正确地创建。使用以下命令调试问题—并特别注意数据类型:

SHOW CREATE TABLE table1;
SHOW CREATE TABLE table2;

You might also want to check that the row you expect in the result set really does exist in both tables:

您可能还想检查您期望的结果集中的行是否确实存在于两个表中:

SELECT * FROM table1 WHERE app_id = '12003';
SELECT * FROM table2 WHERE app_id = '12003';

#3


0  

A regular inner join should suffice:

一个正常的内在连接就足够了:

select t1.app_name, t1.app_id from table1 t1 inner join table2 t2 on t1.app_id = t2.app_Id

#1


3  

SELECT Table1.app_name, Table1.app_id
FROM Table1
INNER JOIN Table2 ON Table1.app_id = Table2.app_id

#2


1  

The query you posted should work (although I would strongly recommend that you use the JOIN keyword rather than the comma syntax).

您发布的查询应该有效(尽管我强烈建议您使用JOIN关键字,而不是使用逗号语法)。

I suspect that your problem is that your tables have not been created correctly. Use the following commands to debug the problem - and pay particular attention to the data types:

我怀疑您的问题是您的表没有被正确地创建。使用以下命令调试问题—并特别注意数据类型:

SHOW CREATE TABLE table1;
SHOW CREATE TABLE table2;

You might also want to check that the row you expect in the result set really does exist in both tables:

您可能还想检查您期望的结果集中的行是否确实存在于两个表中:

SELECT * FROM table1 WHERE app_id = '12003';
SELECT * FROM table2 WHERE app_id = '12003';

#3


0  

A regular inner join should suffice:

一个正常的内在连接就足够了:

select t1.app_name, t1.app_id from table1 t1 inner join table2 t2 on t1.app_id = t2.app_Id