11

我有什么:下一个结构:

table_zero
-> id (PRIMARY 自动递增)
-> other

table_1
-> id (表零 id 的外键)
-> varchar(80) 示例值:(aahellobbb)
-> one_field

table_2
-> id (表零 id 的外键)
-> varchar(160) 示例值:(aaececehellobbb)
-> other_field

我想要什么:搜索并获取一个 (id,varchar) 数组,其中包含在 varchar 字段上与 LIKE '%str%' 匹配的所有匹配项。例如,如果我使用“hello”字符串进行搜索,那么我应该得到两个示例值及其各自的 id。这些 id 总是不同的,因为它们是对 PRIMARY KEY 的引用。

我尝试了什么:我尝试使用 UNION ALL,但在我的示例中它不适用于 LIMITS。

4

3 回答 3

15

通过使用UNION,您可能会获得多次具有相同 ID 的行。怎么用LEFT JOIN

如果我理解了你的问题:

SELECT table_zero.id, table_1.varchar_field, table_2.varchar_field
FROM table_zero
  LEFT JOIN table_1 ON table_zero.id = table_1.id
  LEFT JOIN table_2 ON table_zero.id = table_2.id
WHERE table_1.varchar_field LIKE '%str%'
  OR table_2.varchar_field LIKE '%str%'
于 2013-02-27T13:43:30.673 回答
2

试试这个

SELECT *
FROM 
(
SELECT table_zero.id AS ID, table_1.varchar_field AS field
FROM table_zero
  JOIN table_1 ON table_zero.id = table_1.id
WHERE table_1.varchar_field LIKE '%str%'
UNION
SELECT table_zero.id, table_2.varchar_field  AS field
FROM table_zero
  JOIN table_2 ON table_zero.id = table_2.id
) tbl
WHERE 
tbl.field LIKE '%str%'
于 2013-02-27T13:59:44.363 回答
2
SELECT table_zero.id, table_1.varchar_field, table_2.varchar_field
FROM table_zero
  LEFT JOIN table_1 ON table_zero.id = table_1.id
  LEFT JOIN table_2 ON table_zero.id = table_2.id
WHERE table_1.varchar_field LIKE '%str%'
  OR table_2.varchar_field LIKE '%str%'
于 2014-03-18T11:18:08.317 回答