具有2个选定列的查询每行仅返回1列

时间:2015-04-11 09:38:46

标签: php mysql

我正在运行以下查询。

我希望我的结果中的每一行都同时获得user.nameactivities.name,但我似乎只得到activities.name

为什么我没有看到执行实际活动的每个用户的姓名?

SELECT user.name, activities.name 
    FROM user_activities 
    LEFT JOIN user ON user.userid = user_activities.user_id 
    LEFT JOIN activities ON activities.activityid = user_activities.activity_id

输出:

stdClass Object
(
    [0] => Array
        (
            [name] => Bought a House.
        )

    [1] => Array
        (
            [name] => Purchased a game.
        )

    [2] => Array
        (
            [name] => Purchased a game.
        )

)

2 个答案:

答案 0 :(得分:5)

由于他们共享列名,因此请尝试为该列添加别名:

SELECT user.name AS user_name , activities.name AS activity_name

答案 1 :(得分:1)

如果我理解您的问题没有错,您可能需要使用别名来识别将导致非模糊字段的用户名。只需更新您的查询,如下所示,它将根据您的需要生成

SELECT u.name as user_name, a.name as activites_name FROM user_activities ua LEFT JOIN user u ON
    u.userid = ua.user_id LEFT JOIN activities a ON a.activityid
    = ua.activity_id