1

这里我有 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 之外的角色的所有行。并且希望仅当它在用户存储表中匹配时才包含存储角色。在输出中,您可以看到 id=3 不可用,因为它没有来自用户存储的匹配项。

4

2 回答 2

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 )

其他来源

于 2012-12-12T13:12:28.150 回答
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);
于 2012-12-12T13:22:53.083 回答