[英]Select all the roles for a user based on a cross reference table. PDO MySQL sub-query or JOIN
[英]MySQL query cross reference
我正在尋找一個mysql查詢(使用php)一次遍歷每個表,並且只顯示與cross_check.lastmod中的結果不同的結果
音
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);
}
剛剛JOIN
的cross_check
表。
SELECT t_one.*
FROM t_one
JOIN cross_check ON t_one.guid=cross_check.guid
WHERE t_one.lastmod != cross_check.lastmod
但是,每個表仍然有一個查詢(您可以放心使用聯合,但這不會減少查詢的核心數量)。
如果要將它們合並為一個,則可以使用UNION:
[query for t_one]
UNION
[query for t_two]
UNION
[query for t_three]
我覺得這並沒有比執行三個不同的查詢更有效(盡管有直覺,但沒有根據)。
您也可以這樣做(盡管這僅在t_*
guid
之間沒有交叉的情況下才有效;如果有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)
如果您想獲取標簽(而不是ID COALESCE(t_one.name, t_two.pet, t_three.fruit) AS label
也可以放置COALESCE(t_one.name, t_two.pet, t_three.fruit) AS label
。
嘗試使用此查詢,當然替換為foreach循環中的表名。
SELECT origin.guid as guid FROM t_one as origin, cross_check as cross WHERE cross.lastmod != origin.lastmod;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.