MySQL中的UNION问题

时间:2015-05-28 12:17:32

标签: mysql sql

我有两张桌子。

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个值中的每一个都将被输出。

如何解决这个问题?

亲切的问候 约翰

2 个答案:

答案 0 :(得分:0)

我不确定我是否正确理解了找到并找不到格式的逻辑,如果我错了 - 请添加条件r.format IS NOT NULL而不是r.format IS NULL。我认为您不需要使用 union ,您应该使用加入

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
;

我确信这样的事情可以帮到你!

答案 1 :(得分:0)

如果我理解正确,您希望根据 InputStream ins = con.getInputStream(); 上是否存在数据来显示某些消息,并避免多次显示。

考虑以下

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 |
+------+--------+