我有两张桌子
tbl1
和tbl2
tbl1
表包含5列名称ID (
pk),email
,address
,pid
(INDEX),status
(ENUM Y,N)
tbl2
表包含3列id
(pk),pid
(INDEX),domain
当我运行此查询时
SELECT *
FROM tbl1 as l
LEFT JOIN tbl2 as m on l.pid=m.pid
WHERE l.status='Y';
它提供了多条记录。请注意我们正在加入pid,pid都不是主键。请帮助从这两个表中仅获取唯一值。
答案 0 :(得分:0)
您似乎想要根据表中的相对位置加入。一种方法是使用变量进行row_number模拟。
drop table if exists t1,t2;
create table t1(id int, email varchar(5),address varchar(10),pid int,status varchar(1));
create table t2(id int, pid int, domain varchar(5));
insert into t1 values (1,'aa@aa', 'aaaaa',428,'Y'), (2,'bb@bb', 'bbbbb',428,'n'),(3,'cc@cc', 'ccccc',428,'Y') ;
insert into t2 values (1,428,'mmm'),(2,428,'zzz');
select t1.*,t2.*
from
(
select t1.*,
if(t1.pid <> @pid1, @bn1:=@bn1+1,@bn1:=@bn1) BlockNo1,
if(t1.id <> @id1, @rn1:=@rn1+1, @rn1:=1) rowno1,
@pid1:=t1.pid pid1,
@id1:=t1.id p1
from t1
cross join (select @bn1:=0,@rn1:=0, @pid1:=0 ,@id1:=0) r
where status = 'y'
order by t1.pid,t1.id
) t1
join
(
select t2.id t2id,t2.pid t2pid, t2.domain t2domain,
if(t2.pid <> @pid2, @bn2:=@bn2+1,@bn2:=@bn2) BlockNo2,
if(t2.id <> @id2, @rn2:=@rn2+1, @rn2:=1) rowno2,
@pid2:=t2.pid pid2,
@id2:=t2.id p2
from t2
cross join (select @bn2:=0,@rn2:=0, @pid2:=0 ,@id2:=0) r
order by t2.pid,t2.id
) t2 on (t1.blockno1 = t2.blockno2) and (t1.rowno1 = t2.rowno2)
+------+-------+---------+------+--------+----------+--------+------+------+------+-------+----------+----------+--------+------+------+
| id | email | address | pid | status | BlockNo1 | rowno1 | pid1 | p1 | t2id | t2pid | t2domain | BlockNo2 | rowno2 | pid2 | p2 |
+------+-------+---------+------+--------+----------+--------+------+------+------+-------+----------+----------+--------+------+------+
| 1 | aa@aa | aaaaa | 428 | Y | 1 | 1 | 428 | 1 | 1 | 428 | mmm | 1 | 1 | 428 | 1 |
| 3 | cc@cc | ccccc | 428 | Y | 1 | 2 | 428 | 3 | 2 | 428 | zzz | 1 | 2 | 428 | 2 |
+------+-------+---------+------+--------+----------+--------+------+------+------+-------+----------+----------+--------+------+------+
2 rows in set (0.04 sec)