我如何从两张桌子中选择?

时间:2013-05-10 18:56:29

标签: mysql sql

如果我有这两个表:

table_user
Id   name   lname
1    Mark   Brown
2    Martha Fox

table_score_start:
user_Id  score
2        5

table_score_last:
user_Id  score
1        3
2        4

如何显示以下查询结果?

Id name lname得分 1 Mark Brown 3 2 Martha Fox 5 4

我试过

    SELECT table_user.Id, table_user.name, table_user.lname, table_score_start.score,
 table_score_last.score FROM table_user, table_score_start, table_score_last

但它不起作用

我也试过

    SELECT table_user.Id, table_user.name, table_user.lname, table_score_start.score,
 table_score_last.score FROM table_user, table_score_start, table_score_last WHERE table_user.Id = table_score_start.user_Id

我想显示所有记录,甚至包括那些不在一个或两个表格中的记录表table_score_start和table_score_last

7 个答案:

答案 0 :(得分:2)

尝试以下查询:

SELECT u.Id, u.name, u.lname, s.score, l.score FROM table_user u, 
table_score_start s, table_score_last l WHERE u.id = s.user_id
AND u.id = l.user_id

或使用联接:

SELECT u.Id, u.name, u.lname, s.score, l.score FROM table_user u
INNER JOIN table_score_start s ON (u.id = s.user_id)
INNER JOIN table_score_last l ON ( u.id = l.user_id)

您可以在本文中阅读有关MySql JOIN的更多信息:http://dev.mysql.com/doc/refman/5.0/en/join.html

答案 1 :(得分:2)

select a.Id, a.name, a.lname, b.score as start_score, c.score as last_score from table_user a 
inner join table_score_start b on (a.Id = b.user_Id) 
inner join table_score_last c on (a.Id = c.userId)

inner joinleft join取决于您的需求。

答案 2 :(得分:0)

使用mysql JOIN ....

这是一个简单的指南......

http://www.copterlabs.com/blog/optimizing-sql-queries-with-joins/

答案 3 :(得分:0)

SELECT `user`.*, `start`.score, `last`.score 
FROM table_user `user`, table_score_start `start`, table_score_last `last` 
WHERE `start`.user_Id = `user`.Id 
AND `last`.user_Id = `user`.Id;

答案 4 :(得分:0)

这样的事情应该做到这一点:

SELECT u.ID, u.name, u.lname, start.score, last.score
FROM table_user AS u LEFT JOIN table_Score_Start AS Start on u.ID = Start.ID
LEFT JOIN table_Score_last AS Last on u.id = Last.ID

这是我的头顶,但这应该让你在球场。您可能必须进行一些MySQL语法调整,我一直在使用SQL Server。

答案 5 :(得分:0)

当您针对多个表运行SELECT时,还应在这些表之间包含JOIN条件。这是开始阅读JOINS

的地方

尝试以下方法。请不要使用表的别名,这只会使代码更容易阅读,但对执行没有影响。

SELECT  u.Id
        ,u.name
        ,u.lname
        ,ss.score
        ,sl.score
FROM    table_user u
INNER JOIN
        table_score_start ss
ON      ss.user_ID = u.Id
INNER JOIN
        table_score_last sl
ON      sl.user_ID = u.Id  

答案 6 :(得分:0)

在其他答案中,我看到INNER JOIN,但由于您还希望查看不具有开始或结束分数(或两者)的记录,因此您应该使用LEFT JOIN像这样:

SELECT a.Id, a.name, a.lname, b.score as start_score, c.score as last_score 
FROM table_user a 
LEFT join table_score_start b on (a.Id = b.user_Id) 
LEFT join table_score_last c on (a.Id = c.user_Id)