简体   繁体   中英

Why does column_name = (select column_name) work and not column_name=null

I am fetching some rows for my model but the view has so many criteria i was getting tired of writing many models.To make work easier i don't want to write new select statements for every criteria selected so at first i tried to try and still return something from the select even when one of more of the available criteria are/is not supplied by the user.

SELECT * FROM members WHERE member_id = null AND member_club_id = 1 AND membership_year = null;

and returns nothing

Finally i tried

SELECT * FROM members WHERE member_id = (select member_id) AND member_club_id = (select member_club_id=1) AND membership_year = (select membership_year);

and this works correctly.

I am still new to mysql and i wanted to know why this second approach worked.

Of interest is select member_club_id=1 and member_id = (select member_id) for instance.

In member_id = (select member_id) i was thinking this would be read as member_id=member_id since i had no variable called member id and therefore fail.

In select member_club_id=1 i thought i would get unknown column error in member_club_id and therefore fail.

Someone help out.

You can't use = with NULL . Use IS NULL or IS NOT NULL .

see: http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html

in first query you maybe want do this

 SELECT * FROM members WHERE member_id is null 
                         AND member_club_id = 1 
                         AND membership_year is null;
  • there is not in mysql = null but is null

in your second query i dont think this member_id = (select member_id) will do something

its like you saying WHERE member_id = member_id this automatically return true in all cases. Thats why you got it working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM