两个表之间的MYSQL JOIN

时间:2017-03-24 08:56:08

标签: mysql sql join

我需要一些帮助。我有2张桌子

Table1                      Table2
id | user_id                id | user_id | device_token 
1    4                      1        4      7854239213
2    5                      2        4      1232131232
3    9                      3        5      1232132131
                            4        5        1231321312

我需要创建一个查询,该查询将从table1获取第一个id,并为该table1.user_id创建所有device_token,但不选择select。我需要一个带连接的查询。 预期结果:

user_id => 4 
device_token => 7854239213

user_id => 4 
device_token => 1232131232

3 个答案:

答案 0 :(得分:0)

假设您的user_id从1到9

SELECT T1.USER_ID,T2.DEVICE_TOKEN FROM
TABLE1 T1 INNER JOIN
TABLE2 T2 ON T1.USER_ID=T2.USER_ID WHERE T1.USER_ID=FLOOR(RAND(1)*10)

答案 1 :(得分:0)

这应该让你开始:

SELECT Table2.user_id, Table2.device_token FROM Table2 JOIN Table1 on Table1.user_id = Table2.user_id

如果你想要一个特定的ID:

SELECT Table2.user_id, Table2.device_token FROM Table2 JOIN Table1 on Table1.user_id = Table2.user_id WHERE Table2.user_id = 4

我强烈建议您阅读这篇优秀的SitePoint文章,以获取MySQL连接的初学者介绍:

https://www.sitepoint.com/understanding-sql-joins-mysql-database/

答案 2 :(得分:0)

从table1,table2中选择device_token.table2,其中table1.id = table2.id和table1.user_id = table2.user_id和table1.user_id = 4;