mysql中的一对多查询问题

yua3891 2011-04-18 01:54:17
有表1
pid pathurl
1 /upload/2011/04/05/20010405.jpg
2 /upload/2011/04/05/20010406.jpg
3 /upload/2011/04/05/20010407.jpg

有表2
pid attr1
1 方法1
1 方法2
1 方法3
2 方法2
3 方法4
1 方法4


表1与表2是一对多的关系。我现在需要查询出
表2中attr1='方法2'的记录

或查询出
带有方法1并且带有方法2的记录来

出来的记录格式需要是:
pid pathurl attr1
1 /upload/2011/04/05/20010405.jpg 方法2

用group by和having是可以,但效率很低。
...全文
370 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
ACMAIN_CHM 2011-04-18
  • 打赏
  • 举报
回复
[Quote]
我使用了你这个方法不行哦?呵。
SQL语句是:
SELECT t1.stu_id,t1.stu_name,t3.co_id#,t2.co_name
FROM t1
INNER JOIN
t3 ON t3.stu_id = t1.stu_id
WHERE
t3.co_id = 1 AND t3.co_id = 5[/Quote]

你的观察力还需要煅练,或者说你应该更认真的去看别人的回复。
[Quote]
select c.*
from 表2 a inner join 表2 b on a.pid=b.pid
inner join 表1 c on a.pid=c.pid
where a.attr1='方法1' and b.attr1='方法2'[/Quote]
yua3891 2011-04-18
  • 打赏
  • 举报
回复
SELECT t1.stu_id,t1.stu_name,t3.co_id#,t2.co_name
FROM t1
INNER JOIN
t3 ON t3.stu_id = t1.stu_id
WHERE
t3.co_id = 1 AND t3.co_id = 5

t1表
stu_id stu_name
1 aa
2 bb
3 cc

t3表
stu_id co_id
1 1
1 4
2 1
2 3
2 5



我使用了你这个方法不行哦?呵。
SQL语句是:
SELECT t1.stu_id,t1.stu_name,t3.co_id#,t2.co_name
FROM t1
INNER JOIN
t3 ON t3.stu_id = t1.stu_id
WHERE
t3.co_id = 1 AND t3.co_id = 5
ACMAIN_CHM 2011-04-18
  • 打赏
  • 举报
回复
[Quote]a.attr1='方法1' and b.attr1='方法2'
这样肯定查不出记录的吧?因为attr1不可能等于1也等于2吧?[/Quote]
实践是检查真理的唯一标准。
wwwwb 2011-04-18
  • 打赏
  • 举报
回复
或查询出
带有方法1并且带有方法2的记录来。

SELECT * from (表2 a inner join 表2 b on a.pid=b.pid ) inner join 表1 c
on a.pid=c.pid
where a.attr1='方法1' and b.attr1='方法2'

测试通过
yua3891 2011-04-18
  • 打赏
  • 举报
回复
a.attr1='方法1' and b.attr1='方法2'
这样肯定查不出记录的吧?因为attr1不可能等于1也等于2吧?
ACMAIN_CHM 2011-04-18
  • 打赏
  • 举报
回复
select c.*
from 表2 a inner join 表2 b on a.pid=b.pid
inner join 表1 c on a.pid=c.pid
where a.attr1='方法1' and b.attr1='方法2'
yua3891 2011-04-18
  • 打赏
  • 举报
回复
还有啥好方法不?
zhzhenqin 2011-04-18
  • 打赏
  • 举报
回复
建议使用多表关联的方式,不建议使用子查询.效率低
rucypli 2011-04-18
  • 打赏
  • 举报
回复
select *
from tb1 A
where A.pid in (
select pid
from tb2 B
where B.attr1='方法1' and exists(select 1 from tb2 C where B.pid=pid and attr1='方法2')
)

56,873

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧