简体   繁体   English

从多个表中选择MySQL PHP查询

[英]MySQL PHP Query Select from Multiple Tables

I have a search script here, that needs to search multiple tables for a phrase/word using MySQL and PHP. 我这里有一个搜索脚本,该脚本需要使用MySQL和PHP在多个表中搜索短语/单词。 The column name column that is being searched is all the same across tables. 在表中搜索的列name都是相同的。 Any help would be appreciated and here is my code below: 任何帮助将不胜感激,这是我的下面的代码:

<?php
    $filter = $_REQUEST['query'];
    mysql_connect($hostname,$username, $password) or die ("<script language='JavaScript'>alert('Unable to connect to database! Please try again later.'),history.go(-1)</script>");
    mysql_select_db($dbname);
    $query = 'SELECT * FROM (SELECT `name` FROM `voxmoviesfilestable`) a UNION (SELECT `name` FROM `voxadultfilestable`) b UNION (SELECT `name` FROM `voxmixesfilestable`) c UNION (SELECT `name` FROM `voxconcertsfilestable`) d UNION (SELECT `name` FROM `voxmp3filestable`) e UNION (SELECT `name` FROM `voxfilestable`) WHERE `name` REGEXP \''.$filter.'\' ORDER BY `name`;';
    $maxquery = 'SELECT count(*) as cnt FROM `voxmoviesfilestable`, `voxadultfilestable`, `voxmixesfilestable`, `voxconcertsfilestable`, `voxmp3filestable`, `voxfilestable` WHERE `name` REGEXP \''.$filter.'\';';

    $result = mysql_query($query) or die ('Error accessing Database');
?>

The command "select ... from table1, table2, table3..." does not do what it appears you think it does. 命令“从表1,表2,表3 ...中选择...”并没有按照您认为的样子执行。 It does a massive join of every row of every table to every row of every other table. 它将每个表的每一行与其他表的每一行进行大规模连接。 That is very bad. 那是非常糟糕的。 It looks like you want union. 看来您要工会。 But, it isn't that easy as you must get the columns to look alike. 但是,这并不容易,因为您必须使各列看起来相似。 It would look like: 它看起来像:

select * from ((select id, name from table1) a union (select id, name from table2) b union ...) where regexp '$filter' order by name

NOTE: I added parenthesis around the union section about 12 hours after initially writing this. 注意:最初编写此代码后约12小时,我在联合部分周围添加了括号。

The union will take time, but I believe it would be faster than querying each table separately in PHP. 联合将花费一些时间,但是我相信它将比在PHP中分别查询每个表要快。

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

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