这是我的数据库结构。
+---+----+----+----+
|idx|type| id | pw |
+---+----+----+----+
| 1 | S | A | .. |
| 2 | S | B | .. |
| 3 | T | C | .. |
| 4 | T | D | .. |
| 5 | S | E | .. |
| 6 | S | F | .. |
+---+----+----+----+
+---+-----+-----+------+
|idx|grade|class|number|
+---+-----+-----+------+
| 3 | 3 | 8 | 29 |
| 4 | 2 | 10 | 13 |
+---+-----+-----+------+
+---+-------+
|idx|enabled|
+---+-------+
| 3 | N |
| 4 | N |
+---+-------+
我想根据会员类型获取具有特定信息的会员信息。
我的代码是
$result = query("SELECT * FROM `member` WHERE `id` = '...' AND `pw` = '...'");
$member_info = fetch_obj($result);
if ($member_info->type === 'T') {
$result = query("SELECT * FROM `teacher` WHERE `idx` = '...'");
}
else {
$result = query("SELECT * FROM `student` WHERE `idx` = '...'");
}
$specific_info = fetch_obj($result);
但是,我想在一个查询请求中获取所有数据 像:
SET @type = SELECT `type` FROM `member` WHERE `member`.`idx` = '2';
SELECT
CASE @type
WHEN 'S' THEN `member`.*, `student`.*
WHEN 'T' THEN `member`.*, `teacher`.*
END
FROM
CASE @type
WHEN 'S' THEN `member`, `student`
WHEN 'T' THEN `member`, `teacher`
END
WHERE
`member`.`idx` = '2' AND
CASE @type
WHEN 'S' THEN
`student`.`idx` = `member`.`idx`
WHEN 'T' THEN
`teacher`.`idx` = `member`.`idx`
END
;
我该怎么办?
答案 0 :(得分:1)
如果学生和教师表具有相同的列,那么最简单的解决方案可能是UNION 2查询,因为其中一个联合查询不会返回任何内容。
这样的东西,虽然我会指定我想要的列返回而不使用SELECT *
SELECT `member`.*, `student`.*
FROM `member`
INNER JOIN `student`
ON `student`.`idx` = `member`.`idx`
WHERE `member`.`idx` = '2'
AND member.type = 'S'
UNION
SELECT `member`.*, `teacher`.*
FROM `member`
INNER JOIN `teacher`
ON `teacher`.`idx` = `member`.`idx`
WHERE `member`.`idx` = '2'
AND member.type = 'T'
答案 1 :(得分:1)
由于它出现在您的数据中,您的成员表中的Idx列可以代表学生和教师的Idx列,我会进行双左连接。喜欢的东西(我试着永远不要使用select *)
select
m.idx,
m.type,
m.id,
m.pw,
case when s.idx IS NULL then 0 else 1 end as IsStudent,
s.grade,
s.class,
s.number,
case when t.idx IS NULL then 0 else 1 end as IsTeacher,
t.enabled
from
Member m
LEFT JOIN Student s
on m.idx = s.idx
LEFT JOIN Teacher t
on m.idx = t.idx
where
m.idx = 2
然后,在结果集中,您将有两个“标志”(0或1)列IsStudent和IsTeacher,因此您可以有条件地使用其他列,如果它们可用。