2

我有两张表,一张包含所有用户数据,一张包含一些订单。订单始终为一个用户,但由另一个用户制作(用户不能为自己订购)

在订单表中,编辑器和用户只存储了与用户表相对应的 ID。

这里是缩短的表格:

`orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(10) NOT NULL,
  `editor_id` int(10) NOT NULL,
  `reason` char(200) COLLATE utf8_unicode_ci NOT NULL,
  `amount` decimal(10,2) NOT NULL
)

`users` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` char(250) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `password` varchar(32) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `email` varchar(250) COLLATE utf8_unicode_ci NOT NULL DEFAULT ''
)

我想查询其中一个订单,并将 user_id 替换为 user_name,并且 editor_id 也替换为 users 表中的正确名称。这是正常订单查询结果的样子:

[0] => Array
        (
            [id] => 714
            [user_id] => 97
            [editor_id] => 45
            [reason] => Ausgaben Regale 28.09.13
            [amount] => 150.00
        )

这就是我想要的:

[0] => Array
        (
            [id] => 714
            [user_id] => 97
            [editor_id] => 45
            [user_name] => the user name
            [editor_name] => the editor name
            [reason] => Ausgaben Regale 28.09.13
            [amount] => 150.00
        )

我尝试了很多不同的连接,但都没有成功,我很想得到指向正确方向的提示。

4

2 回答 2

2

这个?

SELECT o.id, o.user_id, o.editor_id, u1.name as user_name, u2.name as editor_name,
o.reason, o.amount 
FROM orders o 
INNER JOIN users u1 ON o.user_id = u1.id 
INNER JOIN users u2 ON o.editor_id = u2.id
WHERE o.id = "requested order id"
于 2013-10-01T08:32:07.217 回答
0
SELECT orders.*,user.name as user_name,editor.name as editor_name FROM orders 
inner join users user on orders.user_id=user.id 
inner join users editor on orders.editor_id=editor.id where orders.id="requested id"
于 2013-10-01T09:02:05.463 回答