简体   繁体   中英

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?

By using UNION it cuts my page off, and doesnt even search it properly

    $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. 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.

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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