基于第二个表id从第三个表字段返回值

时间:2012-05-31 17:29:13

标签: mysql join

我有这张桌子

ADDS(1)

+----+--------------+--------------+
| id | name of add  | Date         |
+----+--------------+--------------+
|  1 | Add01        | March 01     |
|  2 | Add02        | March 02     |
|  3 | Add03        | March 03     |
|  4 | Add04        | March 04     |
+----+--------------+--------------+

TYPE OF ADDS(2)

+----+----------+
| id | Add id   |
+----+----------+
| 21 | 1        |  NOTE: Add id of table (2) = id of table (1)
| 22 | 2        |
| 23 | 3        |
| 24 | 4        |
+----+----------+

NAMES OF TYPES(3)

+----+-----------+--------------+
| id | Type id   | Name         |
+----+-----------+--------------+
| 31 | 21        | Text add     |
| 32 | 22        | Banner       | NOTE: Type id of table (3) = id of table (2)
| 33 | 23        | Video add    |
| 34 | 24        | Other        |
+----+-----------+--------------+

我需要这样的报告:

+--------+-----------+--------------+
| Add id | Add name  | Type of add  |
+--------+-----------+--------------+
|  1     | Add01     | Text add     |
|  2     | Add02     | Banner       |
|  3     | Add03     | Video add    |
|  4     | Add04     | Other        |
+--------+-----------+--------------+

(表格(1)中的Add id,表格(1)中的Add name,表格(3)中的Type of add

到目前为止,我可以执行SELECT query LEFT JOIN table 1 and 2,但我不知道如何从表3返回值Name of type。我该怎么办?

4 个答案:

答案 0 :(得分:1)

再次加入表3:

SELECT t1.`id`          AS `Add id`,
       t1.`name of add` AS `Add name`,
       t3.`Name`        AS `Type of add`
FROM   `ADDS` AS t1
  LEFT JOIN `TYPE OF ADDS`   AS t2 ON t2.`Add id`  = t1.`id`
  LEFT JOIN `NAMES OF TYPES` AS t3 ON t3.`Type id` = t2.`id`

答案 1 :(得分:1)

SELECT  ad.id, ad.name,t.name
FROM ADDS ad
LEFT JOIN TYPEADDS ta ON ta.add_id = ad.id
LEFT JOIN TYPES t ON t.id = ta.id 

答案 2 :(得分:1)

SELECT `table1`.`id` AS `Add id`, `table1`.`name_of_add` AS `Add name`, `table3`.`Name` AS `Type of add`
FROM `table1`, `table2`, `table3`
WHERE `table1`.`id` = `table2`.`add_id` AND `table2`.`id` = `table3`.`Type_id`

答案 3 :(得分:1)

尝试此查询:

select ADDS.nameofadds,TYPEOFADDS.ADDid,NAMEOFTYPES.Name
    FROM ADDS 
    JOIN TYPEOFADDS 
         ON  ADDS.id=TYPEOFADDS.ADDid
    JOIN NAMEOFTYPES 
         ON  TYPEOFADDS.id=NAMEOFTYPES.TYPEid