我有个问题要问你,但我还没有找到解决办法,所以我有两张桌子:
dosar
id name date fk_user fk_verificator
1 dosar 1 08/08/14 1 2
users
id name is_admin is_verificator
1 admin Y N
2 verificator N Y
fk_user是指向用户的外键,fk_verificator也是指向用户表的外键,所以我需要创建一个select来获取dosar的2个用户
name date name is_admin is_verificator
dosar1 08/08/14 admin Y N
verificator N Y
我的问题:
$uid = (int) $this->uri->segment(3, 0);
$this->load->database();
$get_dosar = $this->db->query("SELECT * FROM dosar,users WHERE
users.id = dosar.fk_user AND
users.id = dosar.fk_verificator
AND dosar.id_dosar = $uid");
帮帮我,伙计们。
最佳答案
这使用现代连接语法(最好不要在WHERE子句中添加连接条件):
小提琴:
http://sqlfiddle.com/#!9/d6e60/2/0
select d.name, d.date, u.is_admin, u.is_verificator
from dosar d
join users u
on u.id = d.fk_user
or u.id = d.fk_verificator
where d.id = $uid
输出(dosar上的ID#1):
| NAME | DATE | IS_ADMIN | IS_VERIFICATOR |
|---------|-------------------------------|----------|----------------|
| dosar 1 | August, 08 2014 00:00:00+0000 | Y | N |
| dosar 1 | August, 08 2014 00:00:00+0000 | N | Y |
您似乎不想重复与前一行相同的名称或日期值。这应该在PHP中完成,而不是SQL。
因为您总是只选择一个ID,所以在MySQL中也做这件事有点简单(见下文),不过我还是建议在PHP中做这一部分。
select case when rn = 1 then name end as name,
case when rn = 1 then date end as date,
is_admin,
is_verificator
from(select d.name, d.date, u.is_admin, u.is_verificator, @rw := @rw + 1 as rn
from dosar d
join users u
on u.id = d.fk_user
or u.id = d.fk_verificator
cross join (select @rw := 0) r
where d.id = 1) x
输出:
| NAME | DATE | IS_ADMIN | IS_VERIFICATOR |
|---------|-------------------------------|----------|----------------|
| dosar 1 | August, 08 2014 00:00:00+0000 | Y | N |
| (null) | (null) | N | Y |
小提琴:
http://sqlfiddle.com/#!9/d6e60/3/0
关于php - 从带有2个外键的2个表中选择,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25462614/