Join two tables with one common key in MySQL
I have two tables:
Table 1
id app_name app_id
1 name1 12001
2 name2 12002
3 name2 12002
3 name3 12003
And second
Table 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?
In this example correct SQL should show
name3 12003
I already tried all types of JOIN and开发者_StackOverflow中文版 also select * from table1, table2 where table1.app_id=table2.app_id
, but it seems that I am missing something simple.
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.
SELECT Table1.app_name, Table1.app_id
FROM Table1
INNER JOIN Table2 ON Table1.app_id = Table2.app_id
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
The query you posted should work (although I would strongly recommend that you use the JOIN keyword rather than the comma syntax).
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';
精彩评论