在Mysql中修复查询选择

时间:2014-08-24 07:51:14

标签: mysql sql

我有3张桌子。 第一个表包含来自第二个和第三个表的数据。

table_0

id | id_table_1 |id_table_2 | people_id
1        1           0        1
2        0           2        1
3        0           0        1
4        0           1        2

TABLE_1

  id | machine
   1    bmw
   2    reno
     ....

TABLE_2

  id | machine
   1   yamaha
   2   ducati
   ....

我想制作可以获得此结果的选择查询

tabel_0.id | table_0.people_id  | machine(table_1 or table_2) 
    1                1                      bmw
    2                1                      ducati
    3                1                       ""  

我的查询只能从表格(1或2)中获取

select table_0.id, table_0.people_id,table_1.machine from table_0 join table_1
on table_0.id_table_1 = table_1.id and table_0.people_id = 1

但我需要从所有表(table_1和table_2)获取名称机器。 请帮助解决我的疑问。谢谢!

3 个答案:

答案 0 :(得分:1)

看起来您的查询忘记了要加入的第二个表。

SELECT table_0.id, table_0.people_id, table_1.machine, table_2.machine 
FROM table_0 
   JOIN table_1 ON table_0.id_table_1 = table_1.id 
   JOIN table_2 ON table_0.id_table_2 = table_2.id
WHERE table_0.people_id = 1

您可以连接两个机器列以使它们成为一个,这将为您提供此

SELECT 
    table_0.id, table_0.people_id, 
    CONCAT(table_1.machine, ',' , table_2.machine) AS machines
FROM table_0 
   JOIN table_1 ON table_0.id_table_1 = table_1.id 
   JOIN table_2 ON table_0.id_table_2 = table_2.id
WHERE table_0.people_id = 1

就像Dmitry在评论中所述,如果您希望查询从table_1 表2中获取机器,您将使用左连接,进行查询......

SELECT 
    table_0.id, table_0.people_id, 
    CONCAT(table_1.machine, ',' , table_2.machine) AS machines
FROM table_0 
   LEFT JOIN table_1 ON table_0.id_table_1 = table_1.id 
   LEFT JOIN table_2 ON table_0.id_table_2 = table_2.id
WHERE table_0.people_id = 1

答案 1 :(得分:0)

select 
  table_0.id, 
  table_0.people_id,
  table_1.machine AS machine1, 
  table_2.machine AS machine2
from table_0 
LEFT join 
  table_1 on table_0.id_table_1 = table_1.id 
LEFT join 
  table_2 on table_0.id_table_2 = table_2.id 
WHERE table_0.people_id = 1

答案 2 :(得分:0)

有很多选择

选择UNION

(SELECT table_0.id, table_0.people_id, table_1.machine
FROM table_0 
JOIN table_1 ON table_0.id_table_1 = table_1.id 
WHERE table_0.people_id = 1)
UNION
(SELECT table_0.id, table_0.people_id, table_2.machine
FROM table_0 
JOIN table_2 ON table_0.id_table_2 = table_2.id 
WHERE table_0.people_id = 1)

<强> IFNULL

SELECT table_0.id, table_0.people_id, 
       IFNULL(table_1.machine, table_2.machine) AS machine
FROM table_0 
LEFT JOIN table_1 ON table_0.id_table_1 = table_1.id 
LEFT JOIN table_2 ON table_0.id_table_2 = table_2.id
WHERE table_0.people_id = 1

希望有所帮助