我有两张桌子Place and Post,我需要生成一个输出
place
--------------
std_id sch_id
1 1
2 2
3 1
4 3
5 4
6 2
7 5
8 3
9 5
10 4
和
Post
------------
sch1_id sch2_id sch3_id sup_id
1 2 3 1
3 2 4 2
我需要生成以下输出
sup_id sch_id std_id
1 1 1
1 1 3
1 2 2
1 2 6
1 3 4
1 3 8
2 3 4
2 3 8
2 2 2
2 2 6
2 4 5
2 4 10
我试过这个
SELECT pl.std_id,po.sup_id FROM `place` pl,`post` po WHERE pl.sch_id =
po.sch1_id group by po.sup_id
并得到了这个
| std_id | sup_id |
|--------|--------|
| 1 | 1 |
| 4 | 2 |
修改
答案 0 :(得分:3)
只需使用IN()
:
SELECT pl.std_id,pl.sch_id,po.sup_id
FROM `place` pl
INNER JOIN `post` po
ON(pl.sch_id IN(po.sch1_id,po.sch2_id,po.sch3_id))
无需规范化您的数据,但我们非常推荐!!你应该重新考虑你的表结构。
答案 1 :(得分:3)
看起来您想要形成与任何 sch * 值匹配的连接,如果是这样,那么一种方法是在连接中使用多个条件:
select sup_id, sch_id, std_id
from post p
join place pl on pl.sch_id = p.sch1_id
or pl.sch_id = p.sch2_id
or pl.sch_id = p.sch3_id
答案 2 :(得分:2)
您可以尝试取消转动'表格post
使用UNION ALL
:
SELECT pl.std_id, po.sch_id, po.sup_id
FROM `place` pl
JOIN (
SELECT sch1_id AS sch_id, sup_id
FROM `post`
UNION ALL
SELECT sch2_id AS sch_id, sup_id
FROM `post`
UNION ALL
SELECT sch3_id AS sch_id, sup_id
FROM `post`
UNION ALL
SELECT sch4_id AS sch_id, sup_id
FROM `post`
) AS po ON pl.sch_id = po.sch_id