从MySQL中的两个表中选择数据

时间:2013-02-27 13:37:40

标签: mysql select union database-table

我有什么:下一个结构:

table_zero
- > id (带自动增量的PRIMARY)
- >其他

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。

3 个答案:

答案 0 :(得分:11)

通过使用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%'

答案 1 :(得分: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%'

答案 2 :(得分:1)

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%'