表列包含查询

时间:2017-11-23 08:19:46

标签: php mysql

这是我的问题,我试图从表A中选择数据有列填充查询,从表B中选择数据,从表C中选择数据,但表A,B和C不相关。例如下面的例子。

Table A
ID   Title        Query 
1    one       select note_nbr from table B
2    two       select note_nbr from table C  
3    three     select note_nbr from table D

I want output
ID  Title       note_nbr
1    one       122  (from table B)
1    one       153  (from table B)
2    two       224  (from  table C)
3    three     713  (from  table D)
3    three     224  (from  table D)

查询我已尝试使用子查询,但我不知道如何加入,因为不相关。列的名称只是示例

SELECT 
      TES.ID AS ID,
      TES.NTFY_TTL AS TITLE,
      NBR.NBR_ORD AS NOTE 
FROM
     (SELECT 
           A.ID AS ID,
           A.NTFY_TTL AS NTFY_TTL, 
           FROM A.ID A
     ) TES
LEFT JOIN
     (
     SELECT
          B.ID_NOTE AS ID
          B.NOTE_NBR AS NBR_ORD
     FROM 
          B.ID_NOTE B
UNION ALL
     SELECT
          C.ID_NOTE AS ID
          C.NOTE_NBR AS NBR_ORD
     FROM 
          C.ID_NOTE C 
     ) 
NBR ON TES.ID

2 个答案:

答案 0 :(得分:1)

可以在没有关系的情况下加入,但我看不出您希望只有一个人加入(例如)

drop table如果存在a,b,c,d;

create table a(id int, ntf_ttl varchar(6));
create table b(note_nbr int);
create table c(note_nbr int);
create table d(note_nbr int);

insert into a values (1,'one'),(2,'two'),(3,'Threee');
insert into b values(123),(153);
insert into c values(224);
insert into d values(713),(224);

select id,ntf_ttl,note_nbr from a cross join b

result
+------+---------+----------+
| id   | ntf_ttl | note_nbr |
+------+---------+----------+
|    1 | one     |      123 |
|    1 | one     |      153 |
|    2 | two     |      123 |
|    2 | two     |      153 |
|    3 | Threee  |      123 |
|    3 | Threee  |      153 |
+------+---------+----------+
6 rows in set (0.00 sec)

答案 1 :(得分:0)

insert into a values (1,'ID'),(1,'TITLE'),(1,'select note_nbr from table b(*this column query)');
insert into a values (2,'ID'),(2,'TITLE'),(2,'select note_nbr from table c(*this column query)');
insert into b values(123);
insert into c values(123); 

not like this, result
+------+---------+----------+
| id   | ntf_ttl | note_nbr |
+------+---------+----------+
|    1 | one     |      123 |
|    1 | one     |      153 |
|    2 | two     |      123 |
|    2 | two     |      153 |
|    3 | Threee  |      123 |
|    3 | Threee  |      153 |
+------+---------+----------+

我希望你能得到我说的话。所以当查询中的所有数据显示在表a中的id 1中时。所以输出

ID  note_nbr
1   123(*from table b)
2   123(*from table c)