mysql - 结合2个不同条件的表

时间:2012-12-12 13:05:57

标签: mysql sql

这里我有2个表user和userStore

user Table
╔════╦══════╦════════╦═══════════╗
║ ID ║ NAME ║  ROLE  ║ STORECODE ║
╠════╬══════╬════════╬═══════════╣
║  1 ║ A    ║ Admin  ║           ║
║  2 ║ B    ║ Store  ║         1 ║
║  3 ║ C    ║ Store  ║           ║
║  4 ║ D    ║ Client ║           ║
║  5 ║ E    ║ Staff  ║           ║
╚════╩══════╩════════╩═══════════╝

userStore Table
╔════╦══════════╗
║ ID ║ CATEGORY ║
╠════╬══════════╣
║  1 ║ X        ║
║  2 ║ X        ║
╚════╩══════════╝

Output
╔════╦══════╦════════╦═══════════╦══════════╗
║ ID ║ NAME ║  ROLE  ║ STORECODE ║ CATEGORY ║
╠════╬══════╬════════╬═══════════╬══════════╣
║  1 ║ A    ║ Admin  ║           ║          ║
║  2 ║ B    ║ Store  ║         1 ║ X        ║
║  4 ║ D    ║ Client ║           ║          ║
║  5 ║ E    ║ Staff  ║           ║          ║
╚════╩══════╩════════╩═══════════╩══════════╝

我想使用除store之外的角色从user表中获取所有行。并且只有在userstore表中匹配时才想包含商店角色。 在输出中,您可以看到id = 3不可用,因为它没有来自用户存储的匹配。

2 个答案:

答案 0 :(得分:2)

这应该是直截了当的,使用LEFT JOIN

SELECT  a.*, b.*
FROM    user a
        LEFT JOIN userStore b
            ON a.StoreCode = b.ID
WHERE   (a.role <> 'Store') OR 
        (a.role = 'Store' AND NOT b.ID IS NULL )

其他来源

答案 1 :(得分:1)

试试这个:

SELECT u.id, u.name, u.role, u.StoreCode, IFNULL(us.id, '') id, IFNULL(us.Category, '') Category
FROM USER u 
LEFT JOIN userStore us ON u.StoreCode = us.id 
WHERE IF(LOWER(u.role) = 'store', u.StoreCode IS NOT NULL AND u.StoreCode != '', TRUE);