English 中文(简体)
我如何使用我的舱单加入3个表格
原标题:How do I join 3 tables using mysql
  • 时间:2010-08-24 03:24:00
  •  标签:
  • sql
  • mysql

我有以下表格:

TABLE: companies c
FIELDS: id, name, description

TABLE: departments d
FIELDS: id, name, description

TABLE employees e
FIELDS: id, company_id, department_id, name

I m试图获得1公司所有雇员名单,并将部门名称(d. 姓名)列入行文结果。

我的原始询问:

SELECT e.*, c.name as company 
FROM employees e, companies c 
WHERE e.company_id=c.id AND e.company_id=1;

在问询中,我应加上什么,才能把省的名称(d. 姓名)出现在询问的每一行中? 而且,在某些情况下,如果某个公司没有部门,则分部门可能等于零。

感谢大家的帮助!

问题回答
SELECT e.id, e.name, e.department_id, c.name, d.name
FROM employees AS e
LEFT JOIN departments AS d ON e.department_id = d.id
LEFT JOIN companies AS c ON e.company_id = c.id
WHERE e.company_id = 1;

总的来说,只要事先加入任何一栏/表格,你就能够组合在一起。 在这种情况下,你将数据从两个通过雇员数据有关的单独表格中重新计算,其中两个表格都不是共同依赖的,因此你可以命令两个LEFT JOIN线。

同样,随着平等与平等部的加入,你从参加工会的“左边”桌上(在这种情况下,雇员桌上)和右桌(如果是的话)的配对层(伴侣/分行)上接通。 如果在公司或部门都没有配对,那么从这些表格中提取的任何栏目都将是按结果确定的NCL。





相关问题
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 ...

热门标签