0

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

我将按MD搜索

例如:如果匹配 M = 11 AND D = 29 ... 那么将返回 ID(s) 2 , 5

我只能通过这样的一张桌子找到

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

但是如何在多个表中查找?

4

3 回答 3

4

使用UNION两个SELECTs之间的子句

(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
于 2012-11-28T13:20:07.373 回答
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;
于 2012-11-28T13:20:39.990 回答
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;
于 2012-11-28T13:22:54.430 回答