【问题标题】:Easiest way to search in all columns of multiple tables? [duplicate]在多个表的所有列中搜索的最简单方法? [复制]
【发布时间】:2013-05-28 04:21:42
【问题描述】:

我有很多桌子:

d_customers
d_customers
d_news
d_pages
d_products
d_projects
d_sms 

并且我想创建一个搜索表单来搜索在所有表的所有列中输入的任何单词...但是在编写 SQL 代码时,我发现它很长而且令人困惑...谁能告诉我正确的如何做到这一点?

'SELECT * FROM d_customers,d_customers,d_news,d_pages,d_products,d_projects,d_sms
WHERE ' . $nc_make . 'LIKE .....
AND LIKE.... AND LIKE.....  AND LIKE.....  AND LIKE.....  '

我想通过 LIKE 词搜索所​​有表中的所有 coumns...如果我搜索 google 词我想选择所有表中的所有列,其中所有列都像 google

【问题讨论】:

  • nooo..我想用like搜索在所有coulmns中找到我的话...这个代码不要用like搜索...SELECT * FROM information_schema.COLUMNSC WHERE TABLE_SCHEMA = 'YOUR_DATABASE '
  • 如果我有一个像 google 这样的词,并且想搜索所有像 google 这样的词的表,该怎么做?

标签: mysql sql


【解决方案1】:
create table t1(a int);
create table t2(a int, b int);
insert into t1 values (1);
insert into t2 values (1,3);

SELECT *
  FROM (
         (select 't1' as tbl, a as Col1, null as Col2 from t1) 
         union
         (select 't2' as tbl, a as Col1,    b as Col2 from t2)
       ) as U
where U.Col1 = 1 or U.Col2 = 1

结果:

TBL COL1 COL2
t1  1    (null)
t2  1    3

【讨论】:

  • 我得到错误...#1222 - 使用的 SELECT 语句有不同数量的列......我认为它与列类型有关,因为联合与类似的列类型一起使用......你有任何另一个解决方案,因为我无法更改列类型
  • 可以看到,t1表只有一列,而t2表有两列。构建查询时,每个表的列数必须相同,因此使用null as ColX。根据最大列数构建查询。
【解决方案2】:

如果表格相互关联,则将它们连接起来,它们会应用您的条件。

select *
from customers c
inner join pages p
on p.customer_id=c.customer_id
where customer_name like 'xyz'

如果有必要,您无法避免 sql 中的连接和条件,但您可以优化它们。

如果您想使用编程动态生成查询然后想执行,那么在 mysql information_schema 中存储与表相关的所有信息以及该表中包含的字段。您可以使用它来生成动态 sql。

希望这会有所帮助。

【讨论】:

  • 我想通过 LIKE 字搜索所有表格中的所有 coulmns...如果我搜索 google 字我想选择所有表格中的所有列,其中所有列都像 google
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多