根据文本

时间:2018-02-01 14:07:49

标签: mysql sql

我尽可能地尽量简化。给出两个表:

CREATE TABLE house ( `id` INTEGER  NOT NULL, `nb` INTEGER  NOT NULL );

CREATE TABLE room  ( `id` INTEGER  NOT NULL, `body` TEXT );

包含如下数据:

INSERT INTO house VALUES (1, 111);
INSERT INTO house VALUES (2, 222);
INSERT INTO house VALUES (3, 333);
INSERT INTO house VALUES (4, 444);

INSERT INTO room VALUES (1, 'lorem ipsum House NR: 111 dolor sit ames');
INSERT INTO room VALUES (2, 'lorem m House NR: 777 dolor sit ames');
INSERT INTO room VALUES (3, 'lopsu House NR: 32154 dolor sit ames');
INSERT INTO room VALUES (4, 'ipsa House NR: 222 dolor sit ames');
INSERT INTO room VALUES (5, 'ipsa House NR: 222222 dolor sit ames');

我需要是根据 house 获取roomhouse nb的所有数据, room body House NR: [NR] house body之后House NR:之前[NR]以及SELECT * FROM room WHERE body LIKE '%House NR: 111%'; 之后的所有其余字符串/文字的LIKE '%House NR: 111%'之后的字符串{strong> house nb 强。

我尝试了以下内容:

SELECT *, concat('\'%House NR:', nb, '%\'') as value FROM house;

工作正常。然后,我尝试使用SELECT id, nb FROM house h, ( SELECT body FROM room ) AS r WHERE r.body LIKE concat('\'%House NR:', h.nb, '%\'') 生成+----------+----------+---------+--------------------------------------------+ | house.id | house.nb | room.id | room.body | +----------+----------+---------+--------------------------------------------+ | 1 | 111 | 1 | 'lorem ipsum House NR: 111 dolor sit ames' | +----------+----------+---------+--------------------------------------------+ | 2 | 222 | 4 | 'ipsa House NR: 222 dolor sit ames' | +----------+----------+---------+--------------------------------------------+ 动态,如:

$

价值正确。但是如何将所有价值观融合在一起?我试过了:

$$

但不起作用。我做错了什么?

预期结果为两行

$$(selector)

SQL Fiddle to play with here

3 个答案:

答案 0 :(得分:1)

我注意到的主要问题是你没有考虑House NR:和数字之间的空格。假设在House NR:之后总是只有一个空格,那么你可以加入这两个表:

SELECT house.*, room.*
from house 
inner join room on room.body like concat('%House NR: ', house.nb, ' %');

答案 1 :(得分:1)

您可以使用REGEXPGROUP_CONCAT来实现此目的。我假设数据集不是很大。以下示例

SELECT * FROM room 
WHERE body REGEXP 
(SELECT GROUP_CONCAT('House NR: ', nb SEPARATOR '|') as value FROM house);

SQL Fiddle Here

答案 2 :(得分:0)

SQL Server数据库解决方案: 根据您的查询,您可以显式连接而不使用concat功能:

SELECT h.id, h.nb, r.id, r.body
FROM house h,
    (
        SELECT id,
            body
        FROM room
    ) AS r
WHERE  r.body LIKE '%House NR: ' + CONVERT(VARCHAR(10), h.nb) +  '%'