0

如果我有这两个表:

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 score score 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 中的一个或两个表中的记录

4

7 回答 7

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

于 2013-05-10T19:00:41.130 回答
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取决于您的需要。

于 2013-05-10T19:00:47.740 回答
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 中工作。

于 2013-05-10T19:04:22.410 回答
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  
于 2013-05-10T19:05:20.113 回答
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)
于 2013-05-10T19:05:53.130 回答
0

使用 mysql JOIN....

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

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

于 2013-05-10T19:01:11.597 回答
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;
于 2013-05-10T19:02:34.993 回答