简体   繁体   English

搜索Mysql数据库的多个表

[英]Search Multiple Tables of a Mysql Database

I have the following code: 我有以下代码:

    $query = "select * from customer where Surname  like \"%$trimmed%\" OR TitleName  like \"%$trimmed%\" OR PostCode  like \"%$trimmed%\"
  order by Surname";

However, I have another table which I want to search from with the same paramaters(variables) as that. 但是,我有另一个表,我想用相同的参数(变量)搜索。 I know that something like " select * from customer,othertable " might not be possible, Is there a way to do it? 我知道像“ select * from customer,othertable ”这样的东西可能是不可能的,有没有办法做到这一点?

By using UNION it cuts my page off, and doesnt even search it properly 通过使用UNION,它可以关闭我的页面,甚至无法正常搜索

    $query = "select * from customer where Surname  like \"%$trimmed%\" OR TitleName  like \"%$trimmed%\" OR PostCode  like \"%$trimmed%\"
  order by Surname UNION select * from mooring where Number like \"%$trimmed%\"";

您可以使用UNION运算符从多个表中进行搜索。

If your table structures are different you will have to use multiple queries and multiple fragments of code to handle the different type of results. 如果表结构不同,则必须使用多个查询和多个代码片段来处理不同类型的结果。 Alternately, you can select only the similar fields from the two tables using the UNION operator. 或者,您可以使用UNION运算符仅选择两个表中的类似字段。 You can null out the fields that do not match up. 您可以清空不匹配的字段。 Consider this: 考虑一下:

SELECT CustomerID, Surname, PostCode, NULL AS Number, 'CUSTOMER' AS Type 
# Suppose that the 'Number' column does not exist in this table
FROM   Customer
WHERE  Surname   LIKE '%$trimmed%'
OR     TitleName LIKE '%$trimmed%'
OR     PostCode  LIKE '%$trimmed%'

UNION

SELECT MooringID,  Surname, NULL,     Number,         'MOORING'
# Suppose that the 'PostCode' column does not exist in this table
FROM   Mooring
WHERE  Number    LIKE '%$trimmed%'

ORDER BY 2 # ORDER BY goes to the very end of the union query in this case

Your UNION syntax is incorrect. 您的UNION语法不正确。

  1. The number of columns and types must be the same. 列数和类型必须相同。 If this is not the case use two queries. 如果不是这种情况,请使用两个查询。
  2. The ORDER BY must go at the end of your query, not before a UNION. ORDER BY必须在查询结束时,而不是在UNION之前。

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

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