如何从mysql中选择数据以便显示?
我有3张桌子1表:h_test
____________________
| id | pro_id |
| 1 | 111111 |
| 2 | 222222 |
| 3 | 333333 |
| 4 | 444444 |
|__5___|____555555___|
2表:c_test
__________________________________
| id | pro_id | country |
| 1 | 111111 | usa |
| 2 | 111111 | uk |
| 3 | 222222 | usa |
| 4 | 222222 | china |
| 5 | 333333 | usa |
| 6 | 333333 | uk |
| 7 | 444444 | japan |
| 8 | 444444 | usa |
| 9 | 555555 | uk |
|__10__|____555555___|_____japan___|
3表:i_test
__________________________________
| id | pro_id | number |
| 1 | 111111 | 10 |
| 2 | 111111 | 20 |
| 3 | 222222 | 1 |
| 4 | 222222 | 5 |
| 5 | 333333 | 10 |
| 6 | 333333 | 20 |
| 7 | 444444 | 20 |
| 8 | 444444 | 50 |
| 9 | 555555 | 1 |
|__10__|____555555___|_____5_______|
然后我运行此代码
$SQL = "SELECT * FROM h_test INNER JOIN c_test ON c_test.pro_id = h_test.pro_id
INNER JOIN i_test ON i_test.pro_id = h_test.pro_id
WHERE h_test.pro_id != '0' AND c_test.country = 'usa' AND i_test.number > '5' GROUP BY h_test.pro_id order by i_test.number desc ";
在测试代码之后,我得到了这个数据
_______________________________________________
| id | pro_id | country | number |
| 7 | 444444 | usa | 20 |
| 1 | 111111 | usa | 10 |
|__5___|____333333___|_____usa_____|_____10____|
但我想获得这样的数据,如何选择
_______________________________________________
| id | pro_id | country | number |
| 7 | 444444 | usa | 50 |
| 1 | 111111 | usa | 20 |
|__5___|____333333___|_____usa_____|_____20____|
我该怎么做?
答案 0 :(得分:1)
$SQL = "SELECT c.id, c.pro_id, b.country, max(c.number) FROM h_test a
INNER JOIN c_test b ON a.pro_id = b.pro_id
INNER JOIN i_test c ON a.pro_id = c.pro_id
WHERE a.pro_id != '0' AND b.country = 'usa' AND c.number > '5' GROUP BY a.pro_id order by c.number desc";
或
$SQL = "SELECT i_test.id, i_test.pro_id, c_test.country, max(i_test.number) FROM h_test INNER JOIN c_test ON c_test.pro_id = h_test.pro_id INNER JOIN i_test ON i_test.pro_id = h_test.pro_id
WHERE h_test.pro_id != '0' AND c_test.country = 'usa' AND i_test.number > '5' GROUP BY h_test.pro_id order by i_test.number desc ";
答案 1 :(得分:1)
您的查询中必须进行一些调整
$ SQL =" SELECT * FROM h_test INNER JOIN c_test ON c_test.pro_id = h_test.pro_id INNER JOIN i_test ON i_test.pro_id = h_test.pro_id 在哪里h_test.pro_id!=' 0' AND c_test.country =' usa' AND i_test.number> ' 5' AND i_test.pro_id in(SELECT max(pro_id)FROM i_test GROUP BY number)";