簡體   English   中英

Sql選擇列中的數組

[英]Sql select where array in column

在我的查詢中,我使用連接表category_attributes 假設我們有這樣的行:

category_id|attribute_id
1|1
1|2
1|3

我想要滿足以下兩個需求的查詢。 我有一個允許attribute_id's變量(php)。 如果數組是attribute_id的子集,那么應該選擇category_id ,如果不是 - 沒有結果。

第一種情況:

select * from category_attributes where (1,2,3,4) in category_attributes.attribute_id

應該沒有結果。

第二種情況

select * from category_attributes where (1,2,3) in category_attributes.attribute_id

應該給出所有三行(參見開頭的虛擬行)。

所以我想了解標准 SQL in作用的反面。

解決方案

第 1 步:按要檢查的字段對數據進行分組。

步驟 2:將所需值列表與上一步中獲得的記錄左連接。

第 3 步:現在我們有一個包含所需值和表中相應值的列表。 如果第二列存在於表中,則第二列將等於所需值,否則為NULL

步驟 3 輸出

計算右列中​​的空值。 如果等於 0,則表示 table 包含所有必需的值。 在這種情況下,返回表中的所有記錄。 否則,表中必須至少缺少一個必需的值。 因此,不返回任何記錄。


樣本

表“數據”:

表數據

所需值:
10, 20, 50

詢問:

SELECT * 
FROM   Data 
WHERE  (SELECT Count(*) 
        FROM   (SELECT D.value 
                FROM   (SELECT 10 AS value 
                        UNION 
                        SELECT 20 AS value 
                        UNION 
                        SELECT 50 AS value) T 
                       LEFT JOIN (SELECT value 
                                  FROM   Data 
                                  GROUP  BY value) D 
                              ON ( T.value = D.value )) J 
        WHERE  value IS NULL) = 0;

您可以使用group byhaving

select ca.category_id
from category_attributes ca
where ca.attribute_id in (1, 2, 3, 4) 
group by ca.category_id
having count(*) = 4;  -- "4" is the size of the list

這假定該表沒有重復項(這是屬性映射表的典型情況)。 如果有可能,請使用:

having count(distinct ca.attribute_id) = 4

您可以將attribute_id聚合到數組中並比較來自 php.ini 的兩個數組。

SELECT category_id FROM 
(select category_id, group_concat(attribute_id) as attributes from category_attributes
order by attribute_id) t WHERE t.attributes = (1, 2, 3);

但是您需要找到另一種方法來比較數組或確保數組始終是排序的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM