mysql从三个表中选择一个
我有以下表格:mysql从三个表中选择一个,mysql,sql,multiple-tables,Mysql,Sql,Multiple Tables,我有以下表格: | table_one | table_two | table_three | table_four | | t_one_id | t_two_id | t_three_id | t_four_id | // primary key (auto increment) | | two_nid | three_nid | four_nid | // foreign key to table_one.t_one_id | tone_date |
| table_one | table_two | table_three | table_four |
| t_one_id | t_two_id | t_three_id | t_four_id | // primary key (auto increment)
| | two_nid | three_nid | four_nid | // foreign key to table_one.t_one_id
| tone_date | ttwo_date | tthree_date | tfour_date | // time this was posted.
// other fields
以及下面的查询
SELECT `table_two` . * , `table_three` . * , `table_four` . *
FROM `table_two`
JOIN ( `table_three` ) ON `table_three`.`three_nid`=1
JOIN ( `table_four` ) ON table_four`.`four_nid`=1
WHERE `table_two`.`two_nid`=1
以及以下数据:
table_one: 1, 11/08/2011
table_two: 1, 1, 12/08/2011
table_three: 1, 1, 13/08/2011
table_four: 1, 1, 14/08/2011
现在,我的查询一直返回零结果,即使我希望它返回的结果是(在每个表的日期排序时):
我也尝试过以下方法,但没有成功:
SELECT * FROM table_two t2, table_three t3, table_four t4 WHERE t2.two_nid = 1 OR t3.three_nid=1 OR t4.four_nid=1;
我的SQL查询哪里出了问题
提前感谢,如果需要更多信息,请随时询问
SELECT * FROM table1
JOIN table2 ON table1.one_nid=table2.two_nid
JOIN table3 ON table1.one_nid=table3.three_nid
WHERE table1.one_nid=1
。。。当然,这只有在保证table1
中的每一行在其他每个表中都有一个具有相同id的对应行的情况下才会起作用。否则,您应该阅读有关左连接的内容
。。。当然,这只有在保证table1
中的每一行在其他每个表中都有一个具有相同id的对应行的情况下才会起作用。否则,您应该阅读有关左联接的内容。您是否试图“组合”结果?
如果是,请检查关键字。您是否尝试“组合”结果?
如果是,请选中关键字。如果要将每个表中的结果显示为单独的行,则需要进行三次单独的选择,并合并结果。试试这个:
SELECT `table_two` . *
FROM `table_one`
JOIN ( `table_two` ) ON `table_two`.`two_nid`=`table_one`.`t_one_id`
WHERE `table_one`.`t_one_id`=1
UNION
SELECT `table_three` . *
FROM `table_one`
JOIN ( `table_three` ) ON `table_three`.`three_nid`=`table_one`.`t_one_id`
WHERE `table_one`.`t_one_id`=1
UNION
SELECT `table_four` . *
FROM `table_one`
JOIN ( `table_four` ) ON `table_four`.`four_nid`=`table_one`.`t_one_id`
WHERE `table_one`.`t_one_id`=1
如果要将每个表的结果显示为单独的行,则需要进行三次单独的选择,然后合并结果。试试这个:
SELECT `table_two` . *
FROM `table_one`
JOIN ( `table_two` ) ON `table_two`.`two_nid`=`table_one`.`t_one_id`
WHERE `table_one`.`t_one_id`=1
UNION
SELECT `table_three` . *
FROM `table_one`
JOIN ( `table_three` ) ON `table_three`.`three_nid`=`table_one`.`t_one_id`
WHERE `table_one`.`t_one_id`=1
UNION
SELECT `table_four` . *
FROM `table_one`
JOIN ( `table_four` ) ON `table_four`.`four_nid`=`table_one`.`t_one_id`
WHERE `table_one`.`t_one_id`=1