简体   繁体   中英

MYSQL select field1, field2 only where field1 or field2 does not equal text

I have the following 2 SQL syntax that I'm looking to combine into 1 SQL syntax

SELECT sentFrom 
FROM tableName 
WHERE id = :varid 
AND sentFrom != :vartext

SELECT sentTo 
FROM tableName 
WHERE id = :varid 
AND sentTo != :vartext

I guess I should give an example:

MYSQL TABLE

-----------------------------------
sentFrom          sentTo
1                 2
1                 3
2                 1
2                 3

query

select sentFrom where sentFrom != 1 and select sentTo where sentTo != 1

Returns:

sentTo 2 but not sentFrom 1

sentTo 3 but not sentFrom 1

sentFrom 2 but not sentTo 1

sentFrom 2 and sentTo 3

  Syntex of select query is :
 Select Colname1,Colname2,.... from tablename 
        where colname=value and/or ...
        group by cond..
        having cond...
        order by colname, colname asc/desc
======================================
Ex:

  SELECT sentFrom,sentTo  FROM tableName
       WHERE id = :varid AND (sentFrom != :vartext or sentTo != :vartext)

I think this should help.

SELECT a.sentFrom , b.sentTo FROM 
 (SELECT id, sentFrom FROM tableName WHERE id = :varid AND sentFrom != :vartext) a
JOIN 
 (SELECT id, sentTo FROM tableName WHERE id = :varid AND sentTo != :vartext) b
ON a.id = b.id;

If you think, ID is not common in the rows selected in each query then remove the join condition ON a.id = b.id . In that case it will return you the Cartesian product of records of query one to query 2.

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