SQL queries inside IN() clause

≡放荡痞女 提交于 2019-12-13 19:19:47

问题


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


回答1:


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;



回答2:


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



回答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
)


来源:https://stackoverflow.com/questions/20596460/sql-queries-inside-in-clause

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!