简体   繁体   中英

Select DISTINCT with multiple OR in sql query

I am trying to write a query with multiple OR and using DISTINICT for multiple column.But the result is NULL what i am missing in my query. Anyone can help me here please.

SELECT DISTINCT 
   P.user_p_id, 
   P.surl, 
   M.user_id, 
   M.user_p_id 
   FROM users P, page M 
   WHERE (P.user_p_id = '$urlid' OR P.surl = '$urlid' OR M.user_id = '$urlid' OR M.user_p_id = '$urlid')

You should do a proper join with an ON clause:

SELECT DISTINCT 
   P.user_p_id, 
   P.surl, 
   M.user_id, 
   M.user_p_id 
   FROM users P INNER JOIN page M 
   ON M.user_id = P.user_p_id
   WHERE '$urlid' IN (P.user_p_id, P.surl, M.user_id, M.user_p_id)

I use ON M.user_id = P.user_p_id although it's not clear if you want these columns to be matched.
You may change the type of the JOIN to LEFT if this is what you need.

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