从多个表中获取数据

时间:2013-08-07 20:49:34

标签: php mysql

我的广告门户网站有4个表格。 首先,主表名称是广告

+-------------+
| Field       +
+-------------+
| id      +
| ads_title   +
+-------------+

广告表的示例数据;

+----+-----------------+
| id | ads_title       |
+----+-----------------+
| 20 | 2006 CITROEN C4 |
| 27 | EMEKLI OGRETMEN |
| 28 | Harika 10 n     |
| 34 | HATASIZ BOYASIZ |
| 49 | BAYANDAN 2009   |
+----+-----------------+

表示存储在表格中的广告规范。表名为 ads_spc

+---------+
| Field   |
+---------+
| id      |
| key_name|
+---------+

ads_spc表的数据示例;

+----+-------------+
| id | key_name    |
+----+-------------+
|  1 | Date        |
|  2 | Km          |
|  3 | Colr        |
|  4 | Engine      |
|  5 | Pw. Engine  |
|  6 | Oil         |
|  7 | Speed       |
|  8 | Boody Type  |
|  9 | Traction    |
| 10 | Warranty    |
+----+-------------+

最后通过ads_id存储ads_spc的规范值。表格名称为 ads_values

+------------+
| Field      |
+------------+
| id         |
| ads_id     |
| spc_id     |
| value      |
+------------+

例如此表数据

+----+--------+--------+-------+
| id | ads_id | spc_id | value |
+----+--------+--------+-------+
| 25 |     49 |      9 |  2119 |
| 26 |     49 |     10 |  2131 |
| 27 |     34 |      1 |  2010 |
| 28 |     34 |      2 |  8900 |
| 29 |     34 |      3 |     4 |
| 30 |     34 |      4 |    22 |
| 31 |     34 |      5 |    40 |
| 32 |     34 |      6 |    60 |
| 33 |     34 |      7 |    65 |
| 34 |     34 |      8 |    66 |
+----+--------+--------+-------+

我想在数据行中使用这些表格列表广告(表格:广告)及规格(表格:ads_spc)和广告价值(表格:ads_values)。

联盟; ADS + ADS_SPC + ADS_VALUES(可搜索所有值)

我正在使用这个案例:

SELECT SQL_CALC_FOUND_ROWS 
*
FROM ads AS a
LEFT JOIN ads_spc AS aspc 
LEFT JOIN ads_values AS aval ON aval.ads_id=a.id AND aval.spc_id=aspc.spc_id

我如何联合一排? 抱歉我的英文。

1 个答案:

答案 0 :(得分:1)

为什么联盟对你应该加入这些表的联盟没有意义

SELECT v.id, a.ads_title,s.key_name,v.value FROM `ads` a
INNER JOIN `ads_values`  v ON (a.id =v.ads_id)
INNER JOIN `ads_spc` s ON(v.spc_id =s.id) WHERE s.key_name='Color'