SQL两表关联查询,返回结果的问题!
两个表
A表(DATE1)
aid bid img
1 1 1_01.jpg
2 1 1_02.jpg
3 1 1_03.jpg
4 2 2_01.jpg
5 2 2_02.jpg
6 3 3_01.jpg
B表(DATE2)
bid type
1 1
2 1
3 2
要实现的结果是
循环B表中type=2的两条数据,其中要显示根据B的bid到A表中提取一个img 值
--------------------------------
bid:1 1_03.jpg
--------------------------------
bid:2 2_02.jpg
--------------------------------
我是这样写的
SELECT B.bid,A.img FROM DATE2 B LEFT OUTER JOIN DATE1 A ON A.bid = B.bid WHERE (B.type = 1) ORDER BY B.bid DESC limit 0, 2
<---循环开始--->
$bid $img
<---循环结束--->
但是结果却是:
--------------------------------
bid:1 1_03.jpg
--------------------------------
bid:1 1_02.jpg
--------------------------------
到底应该怎么写,才能循环的是 B 表``而不是 A表啊?
------解决方案--------------------create table date1(aid int,bid int,img varchar(10))
insert date1
select 1,1, '1_01.jpg '
union select 2,1, '1_02.jpg '
union select 3,1, '1_03.jpg '
union select 4,2, '2_01.jpg '
union select 5,2, '2_02.jpg '
union select 6,3, '3_01.jpg '
create table date2(bid int,type int)
insert date2
select 1,1
union select 2,1
union select 3,2
select a.bid,img=max(a.img)
from date1 a inner join date2 b ON A.bid = B.bid
where b.type=1
group by a.bid
drop table date1,date2
/*
bid img
----------- ----------
1 1_03.jpg
2 2_02.jpg
(2 row(s) affected)
*/
------解决方案----------------------你的语句加个group by 就可以了
SELECT B.bid,img=max(A.img)
FROM DATE2 B LEFT OUTER JOIN DATE1 A ON A.bid = B.bid
WHERE (B.type = 1)
GROUP BY B.bid
ORDER BY B.bid DESC limit 0, 2