Php SQL查询到不同的表并显示所有
在我的PHPWeb上,我有3种内容类型,它们保存在不同的表上,具有不同的列数 例如:Php SQL查询到不同的表并显示所有,php,mysql,sql,Php,Mysql,Sql,在我的PHPWeb上,我有3种内容类型,它们保存在不同的表上,具有不同的列数 例如: Type 1 (X columns) (example: table_products) Type 2 (Y columns) (example: table_customers) Type 3 (Z columns) (example: table_posts) 我正在做一个搜索系统,在同一个选择中搜索每种类型,最后显示所有结果 例如: I search: foo System searchs on: T
Type 1 (X columns) (example: table_products)
Type 2 (Y columns) (example: table_customers)
Type 3 (Z columns) (example: table_posts)
我正在做一个搜索系统,在同一个选择中搜索每种类型,最后显示所有结果
例如:
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)
现在我有三个不同的函数来对每种类型进行查询,但我不喜欢这样,因为我无法对它进行分页
我需要一次查询三个表。
谢谢你像这样使用联合
(隐式独立)或联合所有人
:
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.
使用UNION
(隐式distinct)或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.
这将显示找到文本的表名
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%'
这将显示找到文本的表名
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%'
您也可以这样做:
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%'
您也可以这样做:
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%'