简体   繁体   中英

SQL Server : multiple column subquery

Let's say I want to query the order number, product number, and quantity of any item in which the product number and quantity match both the product number and quantity of an item in ordid 365 AND the productCategory is "Electronics".

I've tried to do it as follows:

SELECT 
    ordid, prodid, qty
FROM 
    item
WHERE 
    ((prodid, qty) IN (SELECT prodid, qty
                       FROM item
                       WHERE ordid = 365)
     AND productCategory = "Electronics")

But I'm getting the following errors:

An expression of non-boolean type specified in a context where a condition is expected, near ','.

Incorrect syntax near the keyword 'and'.

Am I using the right T-SQL syntax to perform this kind of action?

Thanks in advance!

Use exists . SQL Server doesn't support tuples:

WHERE EXISTS (SELECT 1
              FROM item i2
              WHERE i2.prodid = item.prodid AND i2.qty = item.qty AND
                    i2.ordid = 365
             )

The join with inline view should also be a valid approach

SELECT t1.ordid, t1.prodid, t1.qty
FROM item t1 inner join 
     (select prodid, qty FROM item WHERE ordid=365 AND productCategory="Electronics") t2
         on t1.prodid = t2.prodid and t1.qty = t2.qty 

There is one way you can use the tuple syntax, more correctly called a row-value comparer . It's a bit more messy than ANSI-SQL, but still OK:

SELECT 
    ordid, prodid, qty
FROM 
    item i
WHERE EXISTS (SELECT i.prodid, i.qty
              INTERSECT
              SELECT i2.prodid, i2.qty
              FROM item i2
              WHERE i2.ordid = 365
             )

It looks odd, but it's actually very useful for comparing nullable columns , because INTERSECT compares NULL s as equal.

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