根据第一个表的内容加入表

时间:2012-11-01 01:31:49

标签: php mysql sql

我正在尝试提出一个查询,其中第三个表将加入另外两个。问题是这个第一个表有不同的版本,我需要查询来查看表1中的列,然后选择要加入的正确表,但结果查询必须返回表1中的所有行,只需加入一个额外的表3即可满足WHERe子句的特定行。 这甚至可能吗?

示例:

表1 =用户

表2 =横幅

表3 = UserSettings或AdminSettings或Nothing

查询会说......

WHERE User.rank='admin' LEFT JOIN AdminSettings

WHERE User.rank='user' LEFT JOIN UserSettings

我目前的疑问是:

$query = "SELECT * FROM Users as U WHERE U.user_id = :id ";
$query .= "LEFT JOIN Banners as B ON U.banner_id = B.banner_id ";
$query .= "LEFT JOIN AdminSettings ON U.server_id = AdminSettings.user_id WHERE U.rank='Admin' ";
$query .= "LIMIT 1";

问题是它只显示具有User.rank ='admin'的行,并且不显示User.rank ='user'rest的行。

2 个答案:

答案 0 :(得分:3)

加入table3两次并在select语句中使用CASE

SELECT  a.*,
        b.*
        CASE WHEN a.rank = 'admin' 
            THEN c.user_ID                     -- gets value from AdminSettings
            ELSE d.user_ID                     -- gets value from UserSettings
        END as ColName1,
        CASE WHEN a.rank = 'admin' 
            THEN c.colName                     -- gets value from AdminSettings
            ELSE d.colName                     -- gets value from UserSettings
        END as ColName2
FROM    users a
        INNER JOIN banners b
            ON a.banner_id = b.banner_id
        LEFT JOIN  AdminSettings c
            ON a.server_ID = c.user_ID
        LEFT JOIN UserSettings d
            ON a.server_ID = d.user_ID

答案 1 :(得分:2)

尝试在字段列表中使用IF子句,如下所示:

$query = "SELECT field1, field2, field3, IF(User.rank = 'admin', A.field, B.field)";
$query .= " FROM Users as U";
$query .= " LEFT JOIN Banners as B ON U.banner_id = B.banner_id";
$query .= " LEFT JOIN AdminSettings as A ON U.server_id = A.user_id";
$query .= " LIMIT 1";

这样的事情应该可以解决问题。