如何使用一个查询查询相关的三个相关表

时间:2010-08-26 20:27:11

标签: mysql join

我有三张桌子。关系是使用中间表 report_freq_map 将每个 report_param report_frequency 绑定在一起。是否可以构造一个SQL,以便用户可以使用frequency ='daily'等约束选择所有report_param行,而不是使用frequency ='1'。

谢谢, -Peter

mysql> describe report_params;
+---------------+------------------+------+-----+---------+----------------+
| Field         | Type             | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+----------------+
| id            | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| test_level    | varchar(45)      | NO   |     | NULL    |                |
| sequence_name | varchar(45)      | NO   |     | NULL    |                |
| step_name     | varchar(45)      | NO   |     | NULL    |                |
| descriptions  | text             | NO   |     | NULL    |                |
+---------------+------------------+------+-----+---------+----------------+
mysql> describe report_frequency;
+-----------+------------------+------+-----+---------+----------------+
| Field     | Type             | Null | Key | Default | Extra          |
+-----------+------------------+------+-----+---------+----------------+
| id        | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| frequency | varchar(25)      | YES  |     | NULL    |                |
+-----------+------------------+------+-----+---------+----------------+

mysql> describe report_freq_map;
+-----------+---------+------+-----+---------+-------+
| Field     | Type    | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| report_id | int(11) | NO   | PRI | 0       |       |
| freq_id   | int(11) | NO   | PRI | 0       |       |
+-----------+---------+------+-----+---------+-------+

2 个答案:

答案 0 :(得分:2)

尝试使用JOIN加入表:

SELECT report_params.*
FROM report_params
JOIN report_freq_map ON report_id = report_params.id
JOIN report_frequency ON freq_id = report_frequency.id
WHERE frequency = 'daily'

答案 1 :(得分:0)

SELECT report_params.id, test_level, sequence_name, step_name, descriptions
FROM report_params
JOIN report_freq_map
ON report_params.id = report_id
JOIN report_frequency
ON freq_id = report_frequency.id
WHERE frequency = 'daily'

(如果您想允许多个频率,则在SELECT之后添加DISTINCT,或者您可能有重复的条目)