简体   繁体   English

SQL查询到不同的表并显示全部

[英]SQL query to different tables and show all

On my php web I have 3 content type saved on different tables with different number of columns 在我的php网站上,我将3种内容类型保存在具有不同列数的不同表上

for example: 例如:

Type 1 (X columns) (example: table_products)
Type 2 (Y columns) (example: table_customers)
Type 3 (Z columns) (example: table_posts)

I'm making a Search system that searchs on each type in the same Select, showing finally all results. 我正在创建一个搜索系统,它可以在同一Select中搜索每种类型,最后显示所有结果。

Example: 例:

I search: foo

System searchs on: Type 1, type 2 and type 3 "foo" and shows:

- Product foo1
- Product foo2
- Customer foo1
- Customer foo2
- Customer foo3
- Post foo1
 (It's only an example)

Now I have three different functions to make the query on each type, but I don't like this because I can't paginate it. 现在,我有三种不同的功能可以对每种类型进行查询,但是我不喜欢这样做,因为我无法对它进行分页。

I need to make a query that searchs on three tables at time. 我需要进行一次查询,一次查询三个表。

Thank you 谢谢

This will show the tableName on where the text has been found. 这将在找到文本的位置显示tableName。

SELECT 'Product' tableName, type1
FROM table_product
WHERE type1 LIKE '%foo%'
UNION
SELECT 'Customer' tableName, type2
FROM table_Customer
WHERE type2 LIKE '%foo%'
UNION
SELECT 'posts' tableName, type3
FROM table_posts
WHERE type3 LIKE '%foo%'

Use UNION (implicit distinct) or UNION ALL like so: 像这样使用UNION (隐式不同)或UNION ALL

SELECT Name FROM table_products  WHERE Name LIKE '%Foo%'
UNION ALL
SELECT Name FROM table_customers WHERE Name LIKE '%Foo%'
UNION ALL
SELECT Name FROM table_posts     WHERE Name LIKE '%Foo%'
-- This is only an example too.

You can also do so: 您也可以这样做:

SELECT *
FROM(
  SELECT 1 AS Type, MyColumn FROM table_product
  UNION ALL
  SELECT 2 AS Type, MyColumn FROM table_customers
  UNION ALL
  SELECT 3 AS Type, MyColumn FROM table_posts
) AllResults
WHERE AllResults.MyColumn LIKE '%foo%'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM