English 中文(简体)
SQL 将两个表格合并到一个表格
原标题:SQL join 2 tables to 1 table
  • 时间:2012-05-24 22:35:55
  •  标签:
  • mysql

I am at the task of joining 3 tables: Task, Unit, and Building.

The task table has a column for a unit and a column for a building.
Any single task is assigned to only a building OR a unit, never both. Thus one column in every record is always null. There are 6100 records in the task table.

当我使用这个join:

select * from task t
join building b on b.id = t.building_id;

我有628排,这是建筑工程的正确总数

当我用这支联军

select * from active_task at
inner join unit_template ut on ut.id = at.unit_template_id

I get 5472 rows. This is the correct number of unit tasks. If I add them up 5472+628 =6100 this is the correct # of rows in the task table.

当我运行这个查询时:

select * from task t
inner join unit ut on ut.id = t.unit_id
inner join building bt on bt.id = t.building_id

I get zero rows. I need my query to retrieve 6100 rows. Any help would be appreciated.

"https://i.sstatic.net/ivP6c.jpg" alt="基本ER"/>

最佳回答

尝试左侧加入 :

select * from task t
left join unit ut on ut.id = t.unit_id
left join building bt on bt.id = t.building_id
问题回答
SELECT  *
FROM    task t
LEFT JOIN
        unit ut
ON      ut.id = t.unit_id
LEFT JOIN
        building bt
ON      bt.id = t.building_id
        AND t.unit_id IS NULL

如果您想要两个查询给出的所有匹配, 为什么不能统一 :

SELECT * from task t JOIN building b ON b.id = t.building_id
UNION
SELECT * from active_task at JOIN unit_template ut ON ut.id = at.unit_template_id

只要两个任务表格的字段数量相同,就足够了(否则就过滤选定语句中想要的列)。





相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...

热门标签