将2个选择查询与2个结果连接成一个查询,结果是一个?

时间:2012-08-04 18:59:16

标签: mysql sql database join

我试图完成的是我想从tableA中选择一行,从tableB中选择一行并合并结果(comlumn名称不同)。

tableA的布局是:

+----------------------------+--------------+------+-----+---------------------+----------------+
| Field                      | Type         | Null | Key | Default             | Extra          |
+----------------------------+--------------+------+-----+---------------------+----------------+
| user_id                    | int(11)      | NO   | PRI | NULL                | auto_increment |
| nickname                   | varchar(32)  | NO   |     | NULL                |                |
| password                   | varchar(129) | NO   |     | NULL                |                |
| mafia_id                   | int(11)      | NO   |     | 0                   |                |
+----------------------------+--------------+------+-----+---------------------+----------------+

和tableB这个:

+-------------+-------------+------+-----+---------+----------------+
| Field       | Type        | Null | Key | Default | Extra          |
+-------------+-------------+------+-----+---------+----------------+
| mafia_id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| mafia_name  | varchar(32) | NO   |     |         |                |
| mafia_tag   | varchar(5)  | NO   |     |         |                |
| mafia_color | int(11)     | NO   |     | 0       |                |
| mafia_car   | int(11)     | NO   |     | 0       |                |
| mafia_base  | int(11)     | NO   |     | 0       |                |
+-------------+-------------+------+-----+---------+----------------+

我尝试了类似的查询:

SELECT *
FROM users

WHERE users.nickname = 'Gamer_Z'

UNION

SELECT * FROM mafia
WHERE mafia.mafia_id = (
    SELECT users.mafia_id
    FROM users
    WHERE users.nickname = 'Gamer_Z'
);

和此:

SELECT *
FROM users
WHERE nickname = 'Gamer_Z'
INNER JOIN mafia ON mafia.mafia_id = users.mafia_id;

但是这些查询会出错,我尝试了其他几个但是这些查看看起来很好,很好吗?

我也读过这些问题:

How can I join two tables with different number of rows in MySQL?

Combine Multiple Query Results in MySQL (by column)

但我似乎无法解决我的问题。

我想要的输出格式是:

|users.user_id|users.nickname|users.password|users.mafia_id|mafia.mafia_name|mafia.mafia_tag|mafia.mafia_color|mafia.mafia_car|mafia.mafia_base|

如何为我在MySQL(5)中尝试完成的内容构建正确的查询? 提前谢谢!

\ EDIT ::


我差点忘了一件事!如果表B中不存在mafia_id,那么stil必须是tableA行被撤销。 (所以用户不在黑手党,我只是加载默认用户数据)

2 个答案:

答案 0 :(得分:2)

您必须将WHERE条件放在JOIN之后,而不是之前:

SELECT    *
FROM      users a
LEFT JOIN mafia b ON a.mafia_id = b.mafia_id
WHERE     a.nickname = 'Gamer_Z'

答案 1 :(得分:0)

加入错误

应该是

SELECT * 来自用户a 加入黑手党b ON a.mafia_id = b.mafia_id和a.nickname ='Gamer_Z'