Using same column multiple times in WHERE clause

前端 未结 8 765
醉话见心
醉话见心 2020-12-15 10:19

I have a following table structure.

USERS

PROPERTY_VALUE

PROPERTY_NAME

USER_

8条回答
  •  一向
    一向 (楼主)
    2020-12-15 10:44

    SELECT * FROM users u
    INNER JOIN user_property_map upm ON u.id = upm.user_id
    INNER JOIN property_value pv ON upm.property_value_id = pv.id
    INNER JOIN property_name pn ON pv.property_name_id = pn.id
    WHERE (pn.id = 1 AND pv.id IN (SELECT id FROM property_value WHERE value 
    like '101') )
    OR ( pn.id = 2 AND pv.id IN (SELECT id FROM property_value WHERE value like 
    '102'))
    
    OR (...)
    OR (...)
    

    You can't do AND because there is no such a case where id is 1 and 2 for the SAME ROW, you specify the where condition for each row!

    If you run a simple test, like

    SELECT * FROM users where id=1 and id=2 
    

    you will get 0 results. To achieve that use

     id in (1,2) 
    

    or

     id=1 or id=2
    

    That query can be optimised more but this is a good start I hope.

提交回复
热议问题