【问题标题】:SQL IN (SELECT statement) where the matched SELECT statement is an array, is this possible?SQL IN(SELECT 语句),其中匹配的 SELECT 语句是一个数组,这可能吗?
【发布时间】:2019-08-20 00:10:45
【问题描述】:

我有两个数据库要匹配结果。其中一个有一个列,该列存储要与另一个表匹配的信息数组。

表格1 ---------------------------------- |收藏ID | items_array | ---------------------------------- | 123 | ['item1' ,'item2'] | ---------------------------------- 表2 --------------------- |用户 ID | item_id | --------------------- | 2 |项目1 | | 1 |项目2 | ---------------------

我想做一个 SQL 查询,该查询将使用 table1.collection_id 来获取 table1.items_array 列,然后获取 table2.item_id 在 table1.items_array 数组中的每个 table2.user_id。我现在的表达是(在 PDO 中):

SELECT
    table2.user_id
FROM table2
WHERE table2.item_id IN (
    SELECT table1.items_array
    FROM table1
    WHERE table1.collection_id = ?
)

所以想法是 IN 语句应该是 items_array 列中的数组。但是,这是行不通的。我尝试以不同的方式格式化 items_array 列中的数组,以查看它是否是语法错误。我尝试了以下方法:

['item1', 'item2']
['item1','item2']
'item1', 'item2'

但他们似乎都没有得到预期的结果。

是否有可能做我希望做的事情,或者我应该寻求以不同的方式存储信息?我想将它存储为一个数组,因为一旦放置了数组,用户将永远不必再次更新或匹配数组,所以我认为不会有规范化问题。

【问题讨论】:

  • 这不是您应该使用关系数据库的方式。您应该有一个表“项目”,其中包含项目的 id 及其名称。一个带有集合 ID 及其名称的表“collection”,然后是另一个带有 collection_id 和 item_id 的表“collections_items”,用于存储集合和项目之间的链接。

标签: mysql arrays pdo


【解决方案1】:

试试下面的查询


SELECT @items := items_array FROM table1 WHERE collection_id = 123;

SELECT table2.user_id
FROM table2
WHERE table2.item_id IN  ( @items );

【讨论】:

    【解决方案2】:

    尝试使用Like 而不是IN。

    with table2 as 
    (
    select item_id ='item1' union select 'item2' union select 'item3' union select 'item4' 
    )
        select item_id from table2 where item_id like  '%' +
        (
        select items_array from
            (
            select items_array = '[''item1'',''item2'']' 
            ) table1
        ) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-23
      • 2021-01-05
      • 2014-12-05
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多