Domanda

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

È stato utile?

Soluzione 3

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
)

Altri suggerimenti

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;

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top