两个查询返回不同的数据

时间:2019-11-21 08:43:17

标签: sql postgresql

我正在根据我运行两个查询,都应该返回相同的结果,但是我认为我缺少了一些东西

SELECT "id", "email", "first_name", "last_name", locale
FROM "users" AS "users"
WHERE (
    EXISTS (
            SELECT cf.field_value, ucf.field_value
            FROM custom_fields cf
            LEFT JOIN users_custom_fields ucf ON cf."id" = ucf.custom_field_id
            WHERE cf."id" = 272 AND
            ((
                cf.field_value = 'true') OR
            (
                ucf.user_id = users.id AND ucf.field_value = 'true'))
    ))

它返回记录

SELECT users.id, cf.field_value, ucf.field_value, ucf.user_id
FROM users
Join custom_fields cf on cf.user_id = users.id
LEFT join users_custom_fields ucf on ucf.custom_field_id = cf."id"
WHERE cf."id" = 272 AND
              ((
                cf.field_value = 'true') OR
              (ucf.user_id = users.id AND ucf.field_value = 'true'))

它不返回任何东西,这两者之间有什么区别吗?

1 个答案:

答案 0 :(得分:1)

第二个查询中,您还使用cf.user_id = users.id将custom_fields表加入。第一个查询没有这个。

添加cf.user_id = users.id后,您的第一个查询就等于第二个查询。

SELECT "id", "email", "first_name", "last_name", locale FROM "users" AS "users" WHERE (
    EXISTS (
    SELECT cf.field_value, ucf.field_value
            FROM custom_fields cf
                LEFT JOIN users_custom_fields ucf ON cf."id" = ucf.custom_field_id
            WHERE cf."id" = 272 
                AND cf.user_id = users.id
                AND (( cf.field_value = 'true') OR
             ( ucf.user_id = users.id AND ucf.field_value = 'true'))
    ))