简体   繁体   中英

Selecting the opposite to the results returned by query

I am trying to simplify my code.

I currently have two querys: one selecting the list of information and outputing it with select boxes to add to a users subscriptions then a second query to select the items that user already has subscribed but I am trying to simplify the code to one query.

I can currently get the code to display the options that the user has subscribed to with check boxes but not the opposite is there a way to select the opposite to the results in a WHERE clause?

$selectionQuery = 'SELECT t1.subId, t1.subTitle FROM tbl_subs t1 LEFT JOIN tbl_list t2 ON t2.subId = t1.subId WHERE t2.userId = '.$id.' AND t1.subId = t2.subId'; 

You already joining the subId at the LEFT JOIN part. Remove the AND t1.subId = t2.subId' from the WHERE part, as it joins again your resultset and overcomes the left join.

Correct:

$selectionQuery = 'SELECT t1.subId, t1.subTitle FROM tbl_subs t1 LEFT JOIN tbl_list t2 ON t2.subId = t1.subId WHERE t2.userId = '.$id.'; 

This code maybe is not ansiSQL but it works perfect on MYSQL.

$selectionQuery = 'SELECT t1.subId, t1.subTitle FROM tbl_subs as t1 WHERE not exists (select 1 from tbl_list as t2 where t2.userId = '.$id.' AND t1.subId = t2.subId)';

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