2012-03-09 169 views
0

我正在尋找一個MySQL查詢(使用PHP)的時間和只顯示效果都高於cross_check.lastmodMySQL查詢交叉引用

t_one

不同經歷的每個表一個
guid | name | lastmod 
1 | Joe | 2012-01-01 01:00:00 
2 | Tom | 2012-01-02 01:00:00 
3 | Sue | 2012-03-01 02:00:00 

t_two

guid | pet | lastmod 
4 | cat | 2012-01-01 01:00:00 
5 | dog | 2012-01-02 01:00:00 
6 | fish | 2012-03-01 02:00:00 

t_three

guid | fruit | lastmod 
7 | orange | 2012-01-01 01:00:00 
8 | pear | 2012-01-02 01:00:00 
9 | grape | 2012-03-01 02:00:00 

cross_check

guid | lastmod 
    1 | 2012-01-01 01:00:00 
    2 | 2012-01-02 01:00:00 
    3 | 2012-01-01 02:00:00 
    4 | 2012-01-01 01:00:00 
    5 | 2012-01-02 01:00:00 
    6 | 2012-01-01 02:00:00 
    7 | 2012-01-01 01:00:00 
    8 | 2012-01-02 01:00:00 
    9 | 2012-01-01 02:00:00 

查詢結果將是:

t_one => 3 | Sue | 2012-03-01 02:00:00 
t_two => 6 | fish | 2012-03-01 02:00:00 
t_three => 9 | grape | 2012-03-01 02:00:00 

到目前爲止我的代碼(需要表交叉引用)

$tables = array('t_one', 't_two', 't_three'); 

    foreach ($tables AS $table) { 

    $query = sprintf("SELECT * FROM '%s'", 
    mysql_real_escape_string($table)); 

    $result = mysql_query($query); 

    } 

回答

4

只是JOINcross_check表中。儘管(你可以放一些工會,但不會減少查詢的核心數量),但每個表仍然有一個查詢。

如果你想將它們組合成一個,你可以使用的UNION:

[query for t_one] 
UNION 
[query for t_two] 
UNION 
[query for t_three] 

我喜歡這種感覺是不是所有的比做三個不同的查詢更有效(一直覺雖然未經證實的要求) 。

你也可以做(雖然這僅適用於如果還有的t_*​​S之間沒有交叉;如果有t_one將受到青睞,那麼t_two):

SELECT COALESCE(t_one.guid,t_two.guid,t_three.guid) AS guid 
FROM cross_check 
LEFT JOIN t_one ON t_one.guid=cross_check.guid 
LEFT JOIN t_two ON t_two.guid=cross_check.guid 
LEFT JOIN t_three ON t_three.guid=cross_check.guid 
WHERE (t_one.lastmod IS NOT NULL AND t_one.lastmod != cross_check.lastmod) 
    OR (t_two.lastmod IS NOT NULL AND t_two.lastmod != cross_check.lastmod) 
    OR (t_three.lastmod IS NOT NULL AND t_three.lastmod != cross_check.lastmod) 

你也可以把COALESCE(t_one.name, t_two.pet, t_three.fruit) AS label,如果你想抓住標籤而不是ID。

0

嘗試使用此查詢,當然,在foreach循環中替換表名。

SELECT origin.guid as guid FROM t_one as origin, cross_check as cross WHERE cross.lastmod != origin.lastmod;