在另一个数组中查找数组值

时间:2015-09-05 12:05:05

标签: mysql regex

我有2个未排序的字符串,例如orange并不总是在第一行或其他值中排在第二位。

 apple, orange, water

 water, juice, orange, something, apple

如果第二行中存在所有第一行值,我想要TRUE。

  • 我已尝试REGEXP 'apple|orange|water',但| or而非and,如果one of them不存在all of them,则表示我为真除非我写下所有可能的类型。

  • 我也试过IN(),但它需要3个语句,如:

    ... 'apple'  IN('water', 'juice', 'orange', 'something', 'apple') AND
        'orange' IN('water', 'juice', 'orange', 'something', 'apple') AND
        'water'  IN('water', 'juice', 'orange', 'something', 'apple') ...
    
  • 还尝试LIKE但在查询时应该像IN()一样。

  • 我毕竟尝试了Match() Against(),但它在join语句中不起作用。看看这个:

    SELECT *
    FROM t1
    INNER JOIN t2
    ON
        t1.sth = t2.sth AND
        MATCH(t1.sthelse) AGAINST(t2.sthelse IN BOOLEAN MODE)
    

    这里有两个问题。首先,它在join中不起作用(也使用where但第二个问题没有解决。其次,AGAINST应该是字符串: - ?Concat()我无法做到这一点错误存在。

我想不是以这些困难的方式做到这一点,也是出于我的目的,我应该用mysql做,并且不能访问php来操纵这些数据。 +我可以将分裂角色改为任何东西。

任何想法......赞赏。

1 个答案:

答案 0 :(得分:0)

我的linux VM仍在加载,因此在MS SQL中测试了以下代码。模式匹配可能会中断。例如,你的第一个字符串是#34; apple,orange,water"你的第二个字符串是#34;苹果派,橙派,水瓶"。

这是将字符串转换为表变量的一个很好的参考。

How to split string and insert values into table in SQL Server

DECLARE @FirstLineValues varchar(max), @SecondLineValues varchar(max)
DECLARE @eachValue VARCHAR(20)
SELECT @FirstLineValues  = 'abc,3,3,5,6,3', @SecondLineValues = 'abc,2,3,4,5,6,7,8,9'
DECLARE @tblFirstLineValues TABLE(Value varchar(10))
DECLARE @tblSecondLineValues Table (value varchar(10))
-------------------------------------------------------------------------
DECLARE @ind int, @allExist bit
SET @ind = CHARINDEX(',',@FirstLineValues)
WHILE @ind > 0
BEGIN
      SET @eachValue = SUBSTRING(@FirstLineValues, 1, @ind-1)
      SET @FirstLineValues = SUBSTRING(@FirstLineValues, @ind+1, LEN(@FirstLineValues)-@ind)
      INSERT INTO @tblFirstLineValues values (@eachValue)
      SET @ind = CharIndex(',', @FirstLineValues)
END
SET @eachValue = @FirstLineValues
INSERT INTO @tblFirstLineValues values (@eachValue)
-------------------------------------------------------------------------
SET @ind = CHARINDEX(',',@SecondLineValues)
WHILE @ind > 0
BEGIN
      SET @eachValue = SUBSTRING(@SecondLineValues,1,@ind-1)
      SET @SecondLineValues = SUBSTRING(@SecondLineValues,@ind+1,LEN(@SecondLineValues)-@ind)
      INSERT INTO @tblSecondLineValues values (@eachValue)
      SET @ind = CharIndex(',',@SecondLineValues)
END
SET @eachValue = @SecondLineValues
INSERT INTO @tblSecondLineValues values (@eachValue)
-------------------------------------------------------------------------
SELECT @allExist = IIF(count(*) = 0, 1, 0)
FROM @tblFirstLineValues flv 
LEFT OUTER JOIN @tblSecondLineValues slv ON flv.value = slv.value 
WHERE slv.value IS NULL
-------------------------------------------------------------------------
select @allExist 'All first line values exist in second line'