以下是表格:
info
+----------------------+
|userid|job_id|position|
+----------------------+
|1 |1 |2 |
|2 |2 |1 |
+----------------------+
job
+----------------+
|job_id|job_title|
+----------------+
|1 |army |
|2 |grocer |
+----------------+
army
+-----------------------+
|position|title |income|
+------------------------+
|1 |private |$125 |
|2 |corporal|$175 |
+------------------------+
grocer
+-----------------------+
|position|title |income|
+-----------------------+
|1 |bagger |$100 |
|2 |cashier|$120 |
+-----------------------+
我想:
+----------------------------+
|id|job_title|position|income|
+----------------------------+
|1 |army |corporal|$175 |
+----------------------------+
每当 id 1 登录并
时+----------------------------+
|id|job_title|position|income|
+----------------------------+
|2 |grocer |bagger |$100 |
+----------------------------+
每当 id 2 被记录在
中时所以,
if job_title=army
then select table army and info.position=army.position
if job_title=grocer
then select table grocer and info.position=grocer.position
我无法弄清楚这一点。我试过了
SELECT * FROM info,job,army,grocer
WHERE userid='$userid' and passid='$passid' and info.job_id=job.job_id;
适用于job_title
但不适用于title
或income
。所以我试过
SELECT * FROM info,job,army,grocer
WHERE userid='$userid' and passid='$passid' and info.job_id=job.job_id and info.position=army.position;
适用于 id 1 但不适用于 id 2 。我需要像
这样的东西SELECT * FROM info,job,army,grocer
WHERE userid='$userid' and passid='$passid' and info.job_id=job.job_id and info.position=_.position;
其中_是军队或杂货店,基于用户ID 和position
答案 0 :(得分:0)
试试这个:
--drop table #info
SELECT *
INTO #info
FROM
(
select 1 as userid , 1 as job_id, 2 as position
UNION
select 2 as userid , 2 as job_id, 1 as position
) a
--drop table #job
SELECT *
into #job
FROM
(
SELECT 1 as job_id , 'army' as job_title
union
SELECT 2 as job_id , 'grocer' as grocer
) a
--drop table #army
SELECT *
into #army
FROM
(
select 1 as position , 'private' as title, 125 as income
union
select 2 as position , 'corporal' as title, 175 as income
) a
--drop table #grocer
SELECT *
into #grocer
FROM
(
select 1 as position , 'bagger' as title, 100 as income
union
select 2 as position , 'cashier' as title, 120 as income
) a
--for whenever id 1 is logged in:
SELECT a.userid as Id, b.job_title, c.title as position, c.income
FROM #info a
inner join #job b
on a.job_id = b.job_id
inner join #army c
on a.position = c.position
where a.userid = 1
--for whenever id 2 is logged in:
SELECT a.userid as Id, b.job_title, c.title as position, d.income
FROM #info a
inner join #job b
on a.job_id = b.job_id
inner join #army c
on a.position = c.position
inner join #grocer d
on c.position = d.position
where a.userid = 2