2015-05-28 37 views
1

我有兩個表。UNION在MySQL中的問題

rp_format

+-----+--+--------------+ 
| fid | | recordformat | 
+-----+--+--------------+ 
| 1 | | CD   | 
| 2 | | Vinyl  | 
| 3 | | DVD   | 
+-----+--+--------------+ 

rp_records

+----+--+--------+ 
| id | | format | 
+----+--+--------+ 
| 1 | |  1 | 
| 2 | |  2 | 
| 3 | |  3 | 
+----+--+--------+ 

我想達成什麼是從 「rp_format」 顯示一切。但我也想檢查一下,看看是否有「格式」中找到的「fid」值。

實例應顯示的頁面上這樣的:

fid   recordformat 
1   CD    Remove this format 
2   Vinyl   Remove this format 
3   DVD    Remove this format 

但是,假設一個「FID」的值在「格式」找到,那麼我想它要顯示這樣的頁面:

fid   recordformat 
1   CD    Remove this format 
2   Vinyl   Can't remove this format 
3   DVD    Remove this format 

「刪除此格式/無法刪除此格式」是將通過使用PHP檢查「fid」=「format」來顯示的文本。

這是到目前爲止我的SQL查詢:

global $wpdb; 
$rpdb = $wpdb->prefix . 'rp_format'; 
$rpdb2 = $wpdb->prefix . 'rp_records'; 

$sql = " 
SELECT * 
FROM $rpdb 
LEFT OUTER JOIN $rpdb2 ON $rpdb.fid = $rpdb2.format 

UNION 

SELECT * 
FROM $rpdb 
RIGHT OUTER JOIN $rpdb2 ON $rpdb.fid = $rpdb2.format 
WHERE $rpdb.fid IS NOT NULL 
"; 

我有此查詢的問題是,當「FID」中的「格式」被找到(比方說,它的發現10次)每這些10價值也將被輸出。

這怎麼解決?

親切的問候 約翰

+0

你能與完整的表更新你的問題嗎?這對於回答很重要。你可以使用[this](http://ozh.github.io/ascii-tables/) – marijnz0r

+1

Better @ marijnz0r? :) –

+0

不清楚,如果在'rp_records.format'上找到'rp_format.fid',那麼它應該顯示'不能刪除這種格式',否則'刪除這種格式'這就是你想要實現的嗎? –

回答

0

如果我理解正確,您希望顯示一些消息,具體取決於是否存在rp_records上的數據,並避免多重顯示。

考慮以下

mysql> select * from rp_format; 
+------+--------------+ 
| fid | recordformat | 
+------+--------------+ 
| 1 | CD   | 
| 2 | Vinyl  | 
| 3 | DVD   | 
| 4 | Test   | 
+------+--------------+ 
4 rows in set (0.00 sec) 

mysql> select * from rp_records; 
+------+--------+ 
| id | format | 
+------+--------+ 
| 1 |  1 | 
| 2 |  2 | 
| 3 |  3 | 
| 4 |  2 | 
| 5 |  1 | 
+------+--------+ 

所以查詢是

select 
f.*, 
case 
    when r.format is not null then 'Can\'t remove' else 'Remove this' end 
as message 
from rp_format f 
left join rp_records r on r.format = f.fid 
group by f.fid ; 


+------+--------------+--------------+ 
| fid | recordformat | message  | 
+------+--------------+--------------+ 
| 1 | CD   | Can't remove | 
| 2 | Vinyl  | Can't remove | 
| 3 | DVD   | Can't remove | 
| 4 | Test   | Remove this | 
+------+--------------+--------------+ 
+0

謝謝!我不知道這種方式是否是最好的解決方案,但我仍然可以使用它並使其適用於我的意圖。 :D我用「1」和「2」替換了文本,並用PHP這樣做:if($ result-> message ==「1」){//做些事情} else {//做其他事情}。所以在某種程度上,它的工作:) –

+0

很高興爲你工作:) –

0

不知道我理解正確,以發現並沒有找到格式的邏輯,如果我錯了 - 添加到,如果條件r.format IS NOT NULL代替r.format IS NULL。我覺得你沒有必要使用工會,你應該使用加入

SELECT 
    r.fid, 
    f.recordformat, 
    IF(r.format IS NULL, "Can't remove this format", "Remove this format") 
FROM rp_format f 
LEFT JOIN rp_records r ON f.fid = r.format 
GROUP BY f.fid 
; 

我相信這樣的事情會幫助你!