在2个表中选择匹配的字符串

时间:2012-11-28 13:18:23

标签: mysql sql select

表A

Id  | M  | D  |   Y   |
=======================
1  | 10  | 28  | 2012 |
2  | 11  | 29  | 2012 |
3  | 12  | 30  | 2012 |

表B

Id  | M  | D  |   Y   |
=======================
4  | 09  | 28  | 2012 |
5  | 11  | 29  | 2012 |
6  | 01  | 30  | 2013 |

我将按 M D

进行搜索

例如:如果匹配M = 11且D = 29 ...那么将返回ID 2 5

我只能通过这样的一个表找到

mysql_query("SELECT * FROM TableA WHERE M='11' AND Y='29' ORDER BY D ASC , Id DESC;";)

但如何在多个表中找到?

3 个答案:

答案 0 :(得分:4)

使用两个UNION s

之间的SELECT子句
(SELECT Id, M, D, Y FROM TableA WHERE M='11' AND Y='29')
UNION
(SELECT Id, M, D, Y FROM TableB WHERE M='11' AND Y='29')
ORDER BY D ASC , Id DESC

答案 1 :(得分:2)

SELECT * FROM TableA WHERE M='11' AND Y='29'
UNION
SELECT * FROM TableB WHERE M='11' AND Y='29'
ORDER BY D ASC , Id DESC;

答案 2 :(得分:2)

您最好使用UNION ALL(如果tableB具有相同的记录)来获取所有记录。否则只需UNION即可。

SELECT * FROM TableA WHERE M='11' AND Y='29'
UNION ALL
SELECT * FROM TableB WHERE M='11' AND Y='29'
ORDER BY D ASC , Id DESC;