SQL queries inside IN() clause

8k views Asked by At

I have SELECT query based on IN() clause, where I want to feed that clause with other queries like:

SELECT *
FROM item_list
WHERE itemNAME
IN (
    SELECT itemNAME
    FROM   item_list
    WHERE  itemID = '17'
    AND    (itemSUB ='1' OR itemSUB ='0')
    ORDER  BY itemSUB DESC
    LIMIT  1,
    SELECT itemNAME
    FROM   item_list
    WHERE  itemID = '57'
    AND    (itemSUB ='0' OR itemSUB ='0')
    ORDER  BY itemSUB DESC
    LIMIT  1
)

But it errors with: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT itemNAME FROM item_list WHERE itemID = '57' AND (itemSUB ='0' OR' at line 11

3

There are 3 answers

0
Szymon Toda On BEST ANSWER

User Goat CO deleted good answer:

SELECT *
FROM item_list
WHERE itemNAME
= ( SELECT itemNAME
    FROM   item_list
    WHERE  itemID = '17'
    AND    (itemSUB ='1' OR itemSUB ='0')
    ORDER  BY itemSUB DESC
    LIMIT  1)
OR itemName 
= ( SELECT itemNAME
    FROM   item_list
    WHERE  itemID = '57'
    AND    (itemSUB ='0' OR itemSUB ='0')
    ORDER  BY itemSUB DESC
    LIMIT  1
)
0
Dan Bracuk On

Here is another way.

SELECT *
FROM item_list
WHERE itemNAME
IN (
SELECT itemNAME
FROM   item_list
WHERE  
(itemID = '17'
AND    (itemSUB ='1' OR itemSUB ='0')
 )
OR
(
itemID = '57' AND    (itemSUB ='0' OR itemSUB ='0')
)

)
ORDER  BY itemSUB DESC
LIMIT  1

However, unless you are practising subqueries, you don't need one. You just need this:

SELECT *
FROM   item_list
WHERE  
(itemID = '17'
AND    (itemSUB ='1' OR itemSUB ='0')
 )
OR
(
itemID = '57' AND    (itemSUB ='0' OR itemSUB ='0')
)
ORDER  BY itemSUB DESC
LIMIT  1
2
Gordon Linoff On

The syntax you are looking for is union all rather than limit:

SELECT *
FROM item_list
WHERE itemNAME
IN (
    SELECT itemNAME
    FROM   item_list
    WHERE  itemID = '17'
    AND    (itemSUB ='1' OR itemSUB ='0')
    ORDER  BY itemSUB DESC
    LIMIT  1 union all
    SELECT itemNAME
    FROM   item_list
    WHERE  itemID = '57'
    AND    (itemSUB ='0' OR itemSUB ='0')
    ORDER  BY itemSUB DESC
    LIMIT  1
)

However, this probably will not work, because some SQL engines (notably MySQL) don't allow limit in such subqueries. Instead, you can do a join:

SELECT il.*
FROM item_list il join
     (select *
      from ((SELECT itemNAME
             FROM   item_list
             WHERE  itemID = '17' AND (itemSUB ='1' OR itemSUB ='0')
             ORDER  BY itemSUB DESC
             LIMIT  1
            ) union
            (SELECT itemNAME
             FROM   item_list
             WHERE  itemID = '57' AND (itemSUB ='0' OR itemSUB ='0')
             ORDER  BY itemSUB DESC
             LIMIT  1
            )
           ) l
     ) l
     on il.itemName = l.itemName;