如何在多个表中搜索并仅显示其中一个表

时间:2016-07-12 08:45:48

标签: php mysql sql

我有三个连接的mysql表。我想在所有三个中搜索几个关键字,但只显示来自AREAS的信息。例如,如果有人搜索名称1'我想在表AREAS中显示区域nr 2行中的信息。

+---------+--+-----------------+--+--------------------------+
| AREAS   |  | RINGS           |  | RINGSLOT                 |
+---------+--+-----------------+--+--------------------------+
| ID | nr |  | areanr | ringnr |  | ringnr | slot | slotname |
+----+----+--+--------+--------+--+--------+------+----------+
| 5  | 1  |  | 2      | 14     |  | 14     | 0    | name1    |
+----+----+--+--------+--------+--+--------+------+----------+
| 6  | 2  |  |        |        |  | 14     | 1    | name2    |
+----+----+--+--------+--------+--+--------+------+----------+
| 7  | 3  |  |        |        |  | 14     | 3    | name 3   |
+----+----+--+--------+--------+--+--------+------+----------+

到目前为止,我已尝试使用各种FOR循环而没有任何成功,但我认为我的查询是正确的,我只是不知道如何从这里处理信息?

mysql_query("(SELECT * 'area' as type FROM areas WHERE nr LIKE '%" . $keyword . "%') 
       UNION
       (SELECT * 'ring' as type FROM rings WHERE ringnr LIKE '%" . $keyword . "%') 
       UNION
       (SELECT ring, namn 'slot' as type FROM ringslot WHERE slotname LIKE '%" . $keyword . "%')";

1 个答案:

答案 0 :(得分:2)

您可以通过仅显示"SELECT DISTINCT A.* FROM areas A LEFT JOIN RINGS r ON(A.nr = r.areanr) LEFT JOIN RINGSLOT rs ON(r.ringnr = rs.ringnr) WHERE r.slotname LIKE '%" . $keyword . "%' OR rs.ringnr LIKE '%" . $keyword . "%' OR A.nr LIKE '%" . $keyword . "%'" table:

中的列来进行连接
{{1}}